【问题标题】:How to execute correctly data-bindings如何正确执行数据绑定
【发布时间】:2012-08-09 19:24:04
【问题描述】:

我需要将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,然后才触发该功能。

【问题讨论】:

  • 我没有时间测试这是否能解决您的整个问题,但对于初学者,您需要在两个绑定表达式中为 ID 添加括号,即:id: 'timer' + ID( )

标签: javascript html data-binding knockout.js


【解决方案1】:

查看此jsFiddle Demo

您可以使用 attr 绑定来设置您的项目的 id。 attr:{ 'id' : 'TIMER_'+id()}

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

然后定义一个 delayInit 绑定,确保在设置 id 值后调用您的函数。它只是在延迟为 0 秒的 SetTimeout 函数中调用您的函数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-29
    • 2021-06-16
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    相关资源
    最近更新 更多