How to load custom KnockoutJS functions using RequireJS?

I have a view model that uses a custom function of an observable array to sort. When I try to run this, it says: "... has no sortByProperty methods."

How to download handlers.js file to do this?

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; }); 
+6
source share
1 answer

You must first verify that KnockoutJS is defined, then download the plugins and finally launch the application. I think all plugins for libraries should be loaded. Here's how you can do it:

 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(); } ); } ); } ); 

I had a lot more libraries, so I reduced it a bit to JQuery and KnockoutJS only, but basically you:

  • declare where your libraries are
  • required to load them
  • you need to download plugins for your libraries, here are the handlers for KnockoutJS
  • download the application (conveniently named ... "application" here :-). Here you must initialize your view models and bind them to DOM elements. Most likely, this is the moment when all the libraries and plugins have been loaded.
+1
source

Source: https://habr.com/ru/post/945060/


All Articles