多次约束问题

时间:2014-06-18 08:04:15

标签: knockout.js typescript

我花了很多时间试图解决这个问题。我怎么能在同一个元素上做两个绑定? 非常感谢任何建议

var app: any = new App();
    app.links.push({
        action: () => {
            $.ajax({   
                type: 'POST',
                url: url
            }).done(data => {                                  
                       require(['App/App'], App=> {
                           console.log("App Filse Loaded");
                           this.app = new App();
                           ko.applyBindings(this.app);// Error "You cannot apply 
                                                      // bindings multiple times 
                                                      // to the same element"
                           this.app.isLoaded(true);
                           this.app.isReady(true);
                       });
            })
        },
        label : 'Create Subscription',
    });           
    ko.applyBindings(app);
});

2 个答案:

答案 0 :(得分:1)

这允许您使用嵌套对象更改同一元素上的模型:

HTML:

<div data-bind="with: model">
    <span data-bind="text: name"></span>
</div>
<button data-bind="click: changeModel">Change Model</button>

的javascript:

$(window).load(function(){
    var model = {
        name: 'John'
    };

    var viewModel = new ViewModel(model);
    ko.applyBindings(viewModel);
});

var ViewModel = function(model) {
    var self = this;

    var nestedViewModel = new NestedViewModel(model);
    self.model = ko.observable(nestedViewModel);

    self.changeModel = function(){
        var model = {
            name: 'Max'
        };

        var nestedViewModel = new NestedViewModel(model);
        self.model(nestedViewModel);
    };
};

var NestedViewModel = function(model) {
    var self = this;

    self.name = model.name;
};

http://jsfiddle.net/Bmc7D/

答案 1 :(得分:1)

我确定在第二次绑定之前的ko.cleanNode会起作用。但这是非常糟糕的做法