如何正确执行数据绑定

时间:2012-08-09 19:24:04

标签: javascript html data-binding knockout.js

我需要为元素分配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,然后才触发函数。

1 个答案:

答案 0 :(得分:3)

结帐jsFiddle Demo

您可以使用attr绑定来设置项目的ID。 attr:{&#39; id&#39; :&#39; TIMER _&#39; + id()}

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

然后定义一个delayInit绑定,确保在设置了id值后调用你的函数。它只需在SetTimeout函数内调用函数,延迟时间为0秒。

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