简体   繁体   中英

function that returns data from an observableArray in knockout

this is the case...

i have a query with this format

{
    query:'A query string',
    user: 'email@user.com.ar',
}

in my view model i have a list of users and a function

var self=this;
self.queries=ko.observableArray(
[
    {
        query:'A query string',
        user: 'email@user.com.ar',
    }
]);
self.users=ko.observableArray(
[
    {user:'email@user.com.ar',data_of_user:{name:'User Name'}}
])
self.getUserInfo=function(email)
{
    var data_user=_.findWhere(self.users(),{email:email});
    return data_user.data_of_user.name;
}

but didnt work

how can i do this but with other approach??

i need to create a span that can pass the email of the user and get the name

<div data-bind="foreach:queries">
    <span data-bind="text:$root.getUserInfo.bind($data,$data.email)">
<div/>

There were some erros I fxed.

View :

<div data-bind="foreach:queries">
    <div data-bind="with: ($root.getUserInfo($data))">
        <!-- user context -->
        <span data-bind="text: email"></span>
        <span data-bind="text: data_of_user.name"></span>      
   </div>
<div/>

JS :

var VM = function () {

    var self = this;
    self.queries = ko.observableArray(
    [{
        query: 'A query string',
        email: 'email@user.com.ar',
    }]);
    self.users = ko.observableArray(
    [{
        email: 'email@user.com.ar',
        data_of_user: {
            name: 'User Name'
        }
    }])
    self.getUserInfo = function (user) {
        var user = _.findWhere(self.users(), {
            'email': user.email
        });
        return user;
    }
    ;
};
ko.applyBindings(new VM());

See Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM