knockout.js api搜索表单

时间:2013-03-18 09:26:06

标签: api knockout.js

我的代码的目标是搜索API搜索字符串:

因此,如果您填写表单,则会获得命中bij名称。

我使用了以下Knockout.js脚本:

var viewModel=
{
    query : ko.observable("wis"),
};

function EmployeesViewModel(query)
{
    var self = this;
    self.employees = ko.observableArray();
    self.query = ko.observable(query);
    self.baseUri = BASE + "/api/v1/search?resource=employees&field=achternaam&q=";

    self.apiurl = ko.computed(function() {
        return self.baseUri + self.query();
    }, self);
    //$.getJSON(baseUri, self.employees);
    //$.getJSON(self.baseUri, self.employees);
    $.getJSON(self.apiurl(), self.employees);
};

$(document).ready(function () {
    ko.applyBindings(new EmployeesViewModel(viewModel.query()));
});

html绑定是:

<input type="text" class="search-query" placeholder="Search" id="global-search" data-bind="value: query, valueUpdate: 'keyup'"/>

但是,如果我填写文本框我onley得到默认的“wis”员工?我做错了什么?

2 个答案:

答案 0 :(得分:0)

不完全确定这里有什么问题,但你调试过它,看看查询的价值在apiurl中是什么?

一个潜在的问题是,您将员工作为可观察对象传递给getJSON,而不是基础数组,因此您可以尝试:

$.getJSON(self.apiurl(), self.employees());

答案 1 :(得分:0)

经过一番挖掘后,我找到了解决方案。

var employeesModel = function(){

        var self = this;

        self.u = base +'/api/v1/search';
        self.resource = 'employees';
        self.field = 'achternaam';
        self.employees = ko.observableArray([]);
        self.q = ko.observable();

        //Load Json when model is setup
        self.dummyCompute = ko.computed(function() {
            $.getJSON(self.u,{'resource': self.resource, 'field': self.field, 'q':self.q }, function(data) {
                    self.employees(data);
             });

        }, self);
    };

    ko.applyBindings(new employeesModel());