I need to assign id attribute to element and after that trigger a function witch will use this unique id.
HTML:
<div class="item-timeleft" data-bind="id: 'timer'+ID, init: zxcCountDown('timer'+ID, 'message', 20)">
</div>
Javascript:
var data = [];
var viewModel = {
item: ko.observableArray(data)
};
ko.applyBindings(viewModel);
$.ajax({
url: 'api/item/all',
dataType: 'json',
success: function (data) {
var item_array = [];
$.each(data, function (index, item) {
item_array[index] = item;
});
viewModel.item(item_array);
console.log(data);
}
});
Additional javascript and custom binding:
ko.bindingHandlers.id = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).attr('id', valueAccessor());
}
};
function zxcCountDown(id, mess, secs, mins, hrs, days) {
var obj = document.getElementById(id);
alert(obj.id);
var oop = obj.oop;
if (!oop) obj.oop = new zxcCountDownOOP(obj, mess, secs, mins, hrs, days);
else {
clearTimeout(oop.to);
oop.mess = mess;
oop.mhd = [mins, hrs, days];
oop.srt = new Date().getTime();
oop.fin = new Date().getTime() + ((days || 0) * 86400) + ((hrs || 0) * 3600) + ((mins || 0) * 60) + ((secs || 0));
oop.end = ((oop.fin - oop.srt));
oop.to = null;
oop.cng();
}
}
Function works just fine when I re-trigger it in console, but somehow I can’t figure out how to assign id and only then trigger the function.
Checkout this jsFiddle Demo
You can use attr binding to set id of your item. attr:{ ‘id’ : ‘TIMER_’+id()}
Then define a delayInit binding which make sure your function called after the id value has been set. It simply call your function inside a SetTimeout function with 0 second delay.