knockoutjs: can we create a dependentObservable function with a parameter?

前端 未结 3 886
忘掉有多难
忘掉有多难 2020-11-30 10:52

I have multiple input boxes that I want to hide/unhide based on a selection from user.

I can achieve this by having a separate dependentObservable for each input an

相关标签:
3条回答
  • 2020-11-30 11:27

    Taking the idea from @Arxisos even further, I came up with this.

    self.showField = function (fieldName)
    {
        return ko.dependentObservable(function () 
        {
            return this.selectedType() ? IsFeatureVisible(this, fieldName) : false;
        }, this)();
    };
    
    0 讨论(0)
  • 2020-11-30 11:38

    In Knockout, bindings are implemented internally using dependentObservables, so you can actually use a plain function in place of a dependentObservable in your bindings. The binding will run your function inside of a dependentObservable, so any observables that have their value accessed will create a dependency (your binding will fire again when it changes).

    Here is a sample: http://jsfiddle.net/rniemeyer/2pB9Y/

    html

    type "one", "two", or "three": <input data-bind="value: text" /> 
    <hr />
    <ul data-bind="template: { name: 'itemTmpl', foreach: items }"></ul>
    

    js

    <script id="itemTmpl" type="text/html">
        <li data-bind="text: name, visible: viewModel.shouldThisBeVisible(name)"></li>
    </script>
    
    var viewModel = {
        text: ko.observable("one"),
        items: [{name: "one"}, {name: "two"}, {name: "three"}],
    };
    
    viewModel.shouldThisBeVisible = function(name) {
        return this.text() === name;
    }.bind(viewModel);
    
    ko.applyBindings(viewModel);
    
    0 讨论(0)
  • 2020-11-30 11:43
    var someOtherViewModel = {
       showField: function(fieldName) {
           return ko.dependentObservable(function () {
               return viewModel.selectedType() ? IsFeatureVisible(viewModel, fieldName) : false;
           }, viewModel);
       }
    };
    

    You can create a function like the one above. The function returns a new dependent observable for the specific field name.

    Now you can do:

    <tr data-bind="visible: someOtherViewModel.showField('Field1')">
    

    Inform me if that code doesn't work - maybe I missed something. Then I'll edit this post.

    0 讨论(0)
提交回复
热议问题