Knockout JS mapping plugin without initial data / empty form

后端 未结 3 1718
梦如初夏
梦如初夏 2020-12-02 21:28

We are using knockout and the knockout mapping plugin to facilitate databinding in our jQTouch web application. The reason we use the mapping plugin, is to be able to use kn

3条回答
  •  温柔的废话
    2020-12-02 21:34

    A couple of options for you besides just manually managing your view model. The mapping plugin supports a create callback that lets you customize how it gets created. This can be used to add default properties to an object, if they happen to be missing.

    Something like this: http://jsfiddle.net/rniemeyer/WQGVC/

    Another alternative is to use a binding that creates properties that are missing. It might look like:

    //create an observable if it does not exist and populate it with the input's value
    ko.bindingHandlers.valueWithInit = {
        init: function(element, valueAccessor, allBindingsAccessor, data) {
            var property = valueAccessor(),
                value = element.value;
    
            //create the observable, if it doesn't exist 
            if (!ko.isWriteableObservable(data[property])) {
                data[property] = ko.observable();
            }
    
            //populate the observable with the element's value (could be optional)
            data[property](value);
    
            ko.applyBindingsToNode(element, { value: data[property] });
        }
    }
    

    You would use it like this (need to pass the property as a string, otherwise it will error):

    
    

    Sample here: http://jsfiddle.net/rniemeyer/JPYLp/

提交回复
热议问题