Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

knockout.js - Passing parameters to a function in knockoutjs viewmodel

I have anchor tag like this

<a href="#" class="btn btn-success order-btn" data-bind="attr:{'data-tiername':$data.tierName, 'data-identifier' : $parent.identifier}, click: $root.setPath.bind($data,$data.tierName, $parent.identifier)">Send values</a>

In the viewmodel

var appViewModel = {
    setPath: function (data, tier, identifier) {
        alert(data);
        alert(tier);
        alert(identifier);
    },
...........
...........
}

The result is some knockoutjs core code being displayed in alert message (possibly definitions of observable(),dependentObservable() functions and [Object object] which is empty when alerted with JSON.stringify)

why does this work?

data-bind="attr:{'data-tiername':$data.tierName, 'data-identifier' : $parent.identifier}

but not this:

click: $root.setPath.bind($data,$data.tierName, $parent.identifier)

note that tierName is an observable(), identifier is computed()

Where can I find more about bind() ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first parameter to bind is the target (what you want this to be) when your function is executed. So, if you want data to be the first argument, then it needs to be the second argument.

Inside your function, if you are dealing with observables or computed observables, then you need to unwrap them to see their value. You would do this either by calling it as a function alert(data()); or by calling alert(ko.utils.unwrapObservable(data)); (which is generally used when you don't know at design type if what you are going to be dealing with is an observable or a non-observable.

The reason that attr and other bindings work when you pass an observable/computed observable is that they all call ko.utils.unwrapObservable for you for convenience (so you don't have to add () when passing observables unless you are writing an expression !$data().

Here is some reference on bind: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...