1

我需要为id元素分配属性,然后触发一个函数,女巫将使用这个唯一的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);
    }
});

附加的 javascript 和自定义绑定:

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();
    }
}

当我在控制台中重新触发它时,函数工作得很好,但不知何故我不知道如何分配 id 然后才触发该函数。

4

1 回答 1

3

Checkout this jsFiddle Demo

You can use attr binding to set id of your item. attr:{ 'id' : 'TIMER_'+id()}

<span data-bind="delayInit : zxcCountDown  , pId : 'TIMER_'+id() , pMessage : 'Hello' , pSecond : 3 , attr:{ 'id' : 'TIMER_'+id()} , text : 'DEMO'"></span>​

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.

var viewModel = {
    id : ko.observable(5) ,
    zxcCountDown : function(id, mess, secs, mins, hrs, days) {
         alert("MESSAGE : "+ mess+ "/ ID : "+id  + "/ SECOND : " + secs);
         alert("My item value :" + document.getElementById(id).textContent);
    }
}

ko.bindingHandlers.delayInit = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var allBindings = allBindingsAccessor() || {};
        if(allBindings) {             
             setTimeout( function() {               
                valueAccessor()(allBindings.pId,allBindings.pMessage, allBindings.pSecond);
             } , 0);        
        }
    }
};

ko.applyBindings(viewModel);
于 2012-08-09T20:31:16.570 回答