使用knockout js实现搜索

时间:2013-10-30 07:04:53

标签: javascript asp.net-mvc mvvm knockout-2.0

这是我的完整代码,我用它来进行搜索。 (我尝试使用SO编辑器最好缩进源代码)

<script type="text/javascript">

    var mapping = {
    'UnitList': {
    create: function (options) {
    return new UnitMapping(options.data);
    }
    },

    'AreaList': {
    create: function (options) {
    return new AreaMapping(options.data);
    }
    }
    }

    $(function () {
    //JSON data from server
    var jsonModel = '{"AreaList":

    [{"AreaName":"area1","AreaDescription":"test","AreaId":5,"PlantId":4,"IsActive":true},{"AreaName":"area2","AreaDescription":"abc","AreaId":6,"PlantId":5,"IsActive":true},{"AreaName":"area3","AreaDescription":"xyz","AreaId":7,"PlantId":6,"IsActive":true},{"AreaName":"area4","AreaDescription":"","AreaId":8,"PlantId":7,"IsActive":true},{"AreaName":"area5","AreaDescription":"","AreaId":9,"PlantId":8,"IsActive":true},{"AreaName":"test","AreaDescription":"test","AreaId":10,"PlantId":4,"IsActive":false}],"UnitList":[{"AreaId":5,"UnitId":1,"UnitName":"test","Description":"test","IsActive":true},{"AreaId":5,"UnitId":2,"UnitName":"test2","Description":"test","IsActive":true}]}';
        var viewModel = ko.mapping.fromJSON(jsonModel, mapping);
    UnitDataService.init(mapping, viewModel);
    });

    var AreaMapping = function (data) {
    ko.mapping.fromJS(data, {}, this);
    };

    var UnitMapping = function (data) {
    ko.mapping.fromJS(data, {}, this);
    this.IsEdit = ko.observable(false);
    this.searchText = ko.observable(""); // added this overservable to capture search text
    };

    var UnitDataService = (function () {
    var mapping,
    viewModel;
    function init(map, model) {
    mapping = map;
    viewModel = model;

    ko.applyBindings(viewModel);
    }

    function editItem(data) {
    data.IsEdit(true);
    }
    function saveItem(data) {
      data.IsEdit(false);
    }

    function templateToUse(context, target)
    {
    return context.IsEdit() ? 'itemEdit' : 'itemDisplay';
    }

    function filteredItems(context)
    {
    return context.viewModel.UnitList.UnitName()

    }
    return {
    init: init,
    templateToUse: templateToUse,
    editItem: editItem,
    saveItem: saveItem,
    filteredItems: filteredItems
    }
    }());
</script>

0 个答案:

没有答案