我有一个View Model,它使用自定义observableArray函数进行排序。当我尝试运行它时,它说:“......没有方法'sortByProperty'”。
我应该如何加载handlers.js文件才能使其正常工作?
handlers.js:
define(['knockout'], function(ko) {
'use strict';
ko.observableArray.fn.sortByProperty = function (prop, order) {
this.sort(function (obj1, obj2) {
var result;
if (obj1[prop] == obj2[prop])
result = 0;
else if (obj1[prop] < obj2[prop])
result = -1;
else
result = 1;
return order === "desc" ? -result : result;
});
};
});
viewmodel.js:
define([
'knockout',
'js/extends/handlers'
], function(ko) {
'use strict';
var LabelsModel = function() {
var self = this;
self.availableLabels = ko.observableArray();
self.selectedLabel = ko.observable();
self.sortBy = ko.observable(); // What field to sort by
self.sortOrder = ko.observable(); // Sort order. asc or desc.
// Returns the labels for the current page
self.pagedRows = ko.computed(function() {
// Sorts the labels
return self.availableLabels.sortByProperty(self.sortBy(), self.sortOrder());
});
};
return LabelsModel;
});
答案 0 :(得分:1)
您必须先确定KnockoutJS已定义,然后加载插件,最后启动您的应用程序。我认为应该如何加载库的所有插件。以下是如何做到这一点:
require.config({
paths: {
jquery: 'libs/jquery-1.9.0.min',
ko: 'libs/knockout-2.2.1.min'
}
});
require(['jquery', 'ko'],
function($, ko) {
// ensure KO is in the global namespace ('this')
if (!this.ko) {
this.ko = ko;
};
requirejs(['handlers'],
function () {
require(['app'],
function(App) {
App.initialize();
}
);
}
);
}
);
我有更多的库,所以我只把它减少到JQuery和KnockoutJS,但基本上你: