Using KnockoutJS, RequireJS (with the text plugin)
http://learn.knockoutjs.com/ is recommended!
The component module:
define(['knockout'], function(ko) {
ko.components.register('app-main', {
viewModel: { require: 'cmp/main/main.vm' },
template: { require: 'text!cmp/main/main.htm' }
});
return function() {};
});
The component view-model:
define(['knockout'], function(ko) {
var SimpleListModel = function() {
var self = this;
self.itemToAdd = ko.observable("");
self.allItems = ko.observableArray(["Fries", "Eggs Benedict", "Ham", "Cheese"]); // Initial items
self.selectedItems = ko.observableArray(["Ham"]); // Initial selection
self.addItem = function () {
if ((self.itemToAdd() != "") && (self.allItems.indexOf(self.itemToAdd()) < 0)) // Prevent blanks and duplicates
self.allItems.push(self.itemToAdd());
self.itemToAdd(""); // Clear the text box
};
self.removeSelected = function () {
self.allItems.removeAll(self.selectedItems());
self.selectedItems([]); // Clear selection
};
self.sortItems = function() {
self.allItems.sort();
};
self.addItemOnEnter = function (data, event) {
try {
if (event.which == 13) {
self.addItem();
return false;
}
return true;
}
catch (e)
{ }
};
};
return SimpleListModel;
});
The component view:
New item:
Your items:
The page main javascript file:
define(["jquery", "knockout"], function () {
'use strict';
var $ = require('jquery');
var ko = require('knockout');
$document.ready(function() {
require(['cmp/main/main'], function() {
var view = $('#content')[0];
ko.cleanNode(view); // clean any previous bindings
$(view).html(' '); // insert our component in the HTML
ko.applyBindings({}, view); // apply bindings to the #content element, so the app-main component is detected
});
});
});
The page HTML:
KnockoutJS components
16700cookie-checkA KnockoutJS dynamic component example using AMD