以编程方式在icheck knockout中添加值

时间:2016-01-17 13:40:53

标签: jquery knockout.js icheck

我正在使用带有淘汰赛的iCheck插件。检查此fiddle。 我想以编程方式检查选项,但它不起作用。当我手动检查一个选项然后它工作。我做错了什么?

我的HTML代码是:

<div class="form-group">
    <label>Condition <span data-bind="text:conditionChecked"></span> </label> //just to check the value in 'conditionChecked'.
        <div class="radio">
            <label>
                <input class="radio i-checks" type="radio" data-bind="iCheck: { checked: conditionChecked }" name="condition" value="new" required /> New
            </label>
        </div>
        <div class="radio">
            <label>
                <input class="radio i-checks" type="radio" data-bind="iCheck: { checked: conditionChecked }" name="condition" value="used" required /> Used
            </label>
        </div>
        <div class="radio">
            <label>
                <input class="radio i-checks" type="radio" data-bind="iCheck: { checked: conditionChecked }" name="condition" value="unboxed" readonly /> unBoxed
            </label>
        </div>
</div>

我的js代码是:

function ViewModel() {
            var self = this;
            self.conditionChecked = ko.observable(false);
            self.loadCondition = function () {
                  //ajax request to get condition value. Suppose ajax request returned value "used". so
                  self.conditionChecked("used");
            }
            self.loadCondition();

            ko.bindingHandlers.iCheck = { // integrating icheck plugin using bh

            init: function (element, valueAccessor) {
                //initialize icheck to the element
                $(element).iCheck({
                    radioClass: 'iradio_square-green'
                });
                $(element).on('ifChecked', function (event) {
                    var observable = valueAccessor();
                    observable.checked(event.target.defaultValue); //assigning selected value
                });
            },
            update: function (element, valueAccessor) {
                var observable = valueAccessor();
            }
        };
}

1 个答案:

答案 0 :(得分:0)

这样做:

  1. 将一个选择器添加到您想要以编程方式选择的输入中(我添加并将$('#unboxed').iCheck('check');标识为其中一个无线电)
  2. 使用ko.applyBindings(new ViewModel())进行检查
  3. 这是一个副作用,但最好使用ko.applyBindings(new ViewModel)代替if (Meteor.isClient) { const VAR_TIME = 'now'; Session.setDefault(VAR_TIME, new Date()); Template.time.helpers({ // <---- HIGH IMPORTANCE now: function() { return Session.get(VAR_TIME); } }); Meteor.setInterval(function tickUpdate() { var date = new Date(); Session.set(VAR_TIME, date); console.log(Session.get(VAR_TIME)); }, 1000); }

    检查小提琴:Fiddle