DatePicker: ui.destroy is not a function - ember.js

I still have the problem with jQuery datepicker in Emberjs. This is my code
If I go away from page with my datepicker, a console gave me error: ui.destroy is not a function.
JQ.Widget = Em.Mixin.create({
didInsertElement: function () {
"use strict";
var options = this._gatherOptions(), ui;
this._gatherEvents(options);
if (typeof jQuery.ui[this.get('uiType')] === 'function') {
ui = jQuery.ui[this.get('uiType')](options, this.get('element'));
} else {
ui = this.$()[this.get('uiType')](options);
}
this.set('ui', ui);
},
willDestroyElement: function () {
"use strict";
var ui = this.get('ui'), observers, prop;
if (ui) {
observers = this._observers;
for (prop in observers) {
if (observers.hasOwnProperty(prop)) {
this.removeObserver(prop, observers[prop]);
}
}
ui._destroy();
}
},
_gatherOptions: function () {
"use strict";
var uiOptions = this.get('uiOptions'), options = {};
uiOptions.forEach(function (key) {
options[key] = this.get(key);
var observer = function () {
var value = this.get(key);
this.get('ui')._setOption(key, value);
};
this.addObserver(key, observer);
this._observers = this._observers || {};
this._observers[key] = observer;
}, this);
return options;
},
_gatherEvents: function (options) {
"use strict";
var uiEvents = this.get('uiEvents') || [], self = this;
uiEvents.forEach(function (event) {
var callback = self[event];
if (callback) {
options[event] = function (event, ui) { callback.call(self, event, ui); };
}
});
}
});
Ember calls willDestroyElement function, but "ui._destroy() is not a function" Why?
This code works fine with outher jQuery elements (Autocomplete,Button ...)

I've had success with the following change:
Replace:
ui._destroy();
With:
if (ui._destroy) ui._destroy();
else if (ui.datepicker) ui.datepicker('destroy');
You may have to add more code if you want to support more UI controls that don't have _destroy().

Related

requirejs + django_select2

I'm building a wagtail / django app using requirejs as js assets combiner, for the site front end.
I'm using it because I've ever been in a kind of JS dependencies hell, where nothing works because of multiple versions of same libs loaded, from different django apps... (I don't even know if it is a good solution)
I've to tell that I'm not a JS expert, and I've none arround me :(
I'm using the good old templates to render the pages, not using angular, react, riot nor vue : I'm a pretty old school dev :)
I've already adapted some scripts to use require, but I'm stuck for now...
I've installed the django_select2 application, and I'm trying to adapt the django_select2.js asset.
I've loaded select2 through bower, and I've updaetd my config.js:
"shim": {
select2: {
deps: ["jquery"],
exports: "$.fn.select2"
}
},
paths: {
...
select2: "select2/dist/js/select2"
}
Then I'm trying to adapt the django_select2.js:
require(['jquery', 'select2'], function ($, select2) {
return (function ($) {
var init = function ($element, options) {
$element.select2(options);
};
var initHeavy = function ($element, options) {
var settings = $.extend({
ajax: {
data: function (params) {
var result = {
term: params.term,
page: params.page,
field_id: $element.data('field_id')
}
var dependentFields = $element.data('select2-dependent-fields')
if (dependentFields) {
dependentFields = dependentFields.trim().split(/\s+/)
$.each(dependentFields, function (i, dependentField) {
result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val()
})
}
return result
},
processResults: function (data, page) {
return {
results: data.results,
pagination: {
more: data.more
}
}
}
}
}, options);
$element.select2(settings);
};
$.fn.djangoSelect2 = function (options) {
var settings = $.extend({}, options);
$.each(this, function (i, element) {
var $element = $(element);
if ($element.hasClass('django-select2-heavy')) {
initHeavy($element, settings);
} else {
init($element, settings);
}
});
return this;
};
$(function () {
$('.django-select2').djangoSelect2();
});
}($));
});
I'm having a Mismatched anonymous define() when running my page in the browser...
I'me realy not a JS expert, I'm coding by trial and error... Could anyone help me with this ?
Thanks !
OK, I have an auto-response...
I've inherited the mixin:
class _Select2Mixin(Select2Mixin):
def _get_media(self):
"""
Construct Media as a dynamic property.
.. Note:: For more information visit
https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property
"""
return forms.Media(js=('django_select2/django_select2.js', ),
css={'screen': (settings.SELECT2_CSS,)})
media = property(_get_media)
class _Select2MultipleWidget(_Select2Mixin, forms.SelectMultiple):
pass
Then I can use the widget:
class DocumentationSearchForm(forms.Form):
...
document_domains = forms.ModelMultipleChoiceField(required=False,
label=_('Document domains'),
queryset=NotImplemented,
widget=_Select2MultipleWidget)
I've set my config.js file for path:
requirejs.config({
paths: {
jquery: 'jquery/dist/jquery',
select2: "select2/dist/js"
},
shim: {
"select2/select2": {
deps: ["jquery"],
exports: "$.fn.select2"
}
}
});
Then I've overridden the django_select2.js file, to wrap the content in a require satement:
require(['jquery', 'select2/select2'], function ($) {
(function ($) {
var init = function ($element, options) {
$element.select2(options);
};
var initHeavy = function ($element, options) {
var settings = $.extend({
ajax: {
data: function (params) {
var result = {
term: params.term,
page: params.page,
field_id: $element.data('field_id')
}
var dependentFields = $element.data('select2-dependent-fields')
if (dependentFields) {
dependentFields = dependentFields.trim().split(/\s+/)
$.each(dependentFields, function (i, dependentField) {
result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val()
})
}
return result
},
processResults: function (data, page) {
return {
results: data.results,
pagination: {
more: data.more
}
}
}
}
}, options);
$element.select2(settings);
};
$.fn.djangoSelect2 = function (options) {
var settings = $.extend({}, options);
$.each(this, function (i, element) {
var $element = $(element);
if ($element.hasClass('django-select2-heavy')) {
initHeavy($element, settings);
} else {
init($element, settings);
}
});
return this;
};
$(function () {
$('.django-select2').djangoSelect2();
});
}($));
});
That's all, folks !

How to define Handlebar.js templates in an external file

I am currently defining my Handlebars templates within the same HTML file in which they will be used.
Is it possible to define them as external templates, which can be called when the page is loaded?
For those that get here through Google search like I did, I finally found the perfect answer in this post, check it out :
http://berzniz.com/post/24743062344/handling-handlebarsjs-like-a-pro
Basically you need to implement a method, getTemplate :
Handlebars.getTemplate = function(name) {
if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
$.ajax({
url : 'templatesfolder/' + name + '.handlebars',
success : function(data) {
if (Handlebars.templates === undefined) {
Handlebars.templates = {};
}
Handlebars.templates[name] = Handlebars.compile(data);
},
async : false
});
}
return Handlebars.templates[name];
};
and then call your template with it :
var compiledTemplate = Handlebars.getTemplate('hello');
var html = compiledTemplate({ name : 'World' });
That way, if you precompiled the templates (great for production use) it will find it directly, otherwise it will fetch the template and compile it in the browser (that's how you work in development).
You can use AJX to load them.
Here's an example function which accepts a URL to a Handlebars template, and a callback function. The function loads the template, and calls the callback function with the compiled Handlebars template as a parameter:
function loadHandlebarsTemplate(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var raw = xhr.responseText;
var compiled = Handlebars.compile(raw);
callback(compiled);
}
};
xhr.send();
}
For example, assume you have a Handlebars template defined in a file named /templates/MyTemplate.html, such as:
<p>The current date is {{date}}</p>
You can then load that file, compile it and render it to the UI, like this:
var url = '/templates/MyTemplate.html';
loadHandlebarsTemplate(url, function(template) {
$('#container').html(template({date: new Date()}));
});
An even better solution, would be to pre-compile the templates which would speed up the time they take to load. More info on precompilation can be found here.
Edited solution from Jeremy Belolo for working more templates in directories, if i do not want to have all templates in templates directory.
Handlebars.getTemplate = function(name, dir) {
if (dir === undefined) //dir is optional
dir = "";
if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
$.ajax({
url : 'templates/' + dir+'/' + name, //Path, dir is optional
success : function(data) {
if (Handlebars.templates === undefined) {
Handlebars.templates = {};
}
if (Handlebars.templates[dir] === undefined) {
Handlebars.templates[dir] = {};
}
if (dir === undefined)
Handlebars.templates[name] = Handlebars.compile(data);
else
Handlebars.templates[dir][name] = Handlebars.compile(data);
},
async : false
});
}
if (dir === undefined)
return Handlebars.templates[name];
else
return Handlebars.templates[dir][name];
};
Using async: false; is far away from being the perfect solution. With jQuery in your toolbox, just make use of $.Deferred.
I came up with this solution:
;(function ($, Handlebars) {
'use strict';
var namespace = window,
pluginName = 'TemplateEngine';
var TemplateEngine = function TemplateEngine(options) {
if(!(this instanceof TemplateEngine)) {
return new TemplateEngine(options);
}
this.settings = $.extend({}, TemplateEngine.Defaults, options);
this._storage = {};
return this;
};
TemplateEngine.Defaults = {
templateDir: './tpl/',
templateExt: '.tpl'
};
TemplateEngine.prototype = {
constructor: TemplateEngine,
load: function(name, $deferred) {
var self = this;
$deferred = $deferred || $.Deferred();
if(self.isCached(name)) {
$deferred.resolve(self._storage[name]);
} else {
$.ajax(self.urlFor(name)).done(function(raw) {
self.store(name, raw);
self.load(name, $deferred);
});
}
return $deferred.promise();
},
fetch: function(name) {
var self = this;
$.ajax(self.urlFor(name)).done(function(raw) {
self.store(name, raw);
});
},
isCached: function(name) {
return !!this._storage[name];
},
store: function(name, raw) {
this._storage[name] = Handlebars.compile(raw);
},
urlFor: function(name) {
return (this.settings.templateDir + name + this.settings.templateExt);
}
};
window[pluginName] = TemplateEngine;
})(jQuery, Handlebars);

unit testing custom knockoutjs binding

How can I unit test this knockoutjs binding where I call a certain function 'myValueAccessor' when the element is swiped on my touchpad?
I am also unsure what the unit should or is able to test at all here.
It would be ok for the first time to assert wether myValueAccessor is called.
But how can I trigger/imitate or should I say mock... the swiperight event?
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
self.myValueAccessor = function () {
location.href = 'set a new url'
};
UPDATE
I have put here my unit test with mocha.js
I can outcomment the 'value()' in the binding but still the test succeeded thats odd.
Is it not correct to put this (as a test):
function (element,args) {
alert('assertion here');
}
as a 3rd parameter into the ko.test function?
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = $(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
//value();
});
});
}
};
// Subscribe the swiperight event to the jquery on function
$.fn.on = function (event, callback) {
if (event === "swiperight") {
callback();
}
};
// Subscribe the fadeOut event to the jquery fadeOut function
$.fn.fadeOut = function (speed, callback) {
callback();
};
ko.test("div", {
tap: function () {
assert.ok(true, "It should call the accessor");
}
}, function () {
});
UPDATE:
custom.bindings.js:
define(['knockout','hammer'], function (ko,Hammer) {
return function Bindings() {
ko.bindingHandlers.tap = {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
};
});
unittest.js:
how can I connect this code to knockout in my test?
UPDATE
The Bindings is injected via require.js from my bindings.js file:
describe("When swiping left or right", function () {
it("then the accessor function should be called", function () {
ko.bindingHandlers.tap = new Bindings();
Hammer.Instance.prototype.on = function (event, callback) {
if (event === "swiperight") {
callback();
}
};
$.fn.fadeOut = function (speed, callback) {
callback();
};
var accessorCalled = false;
ko.test("div", {
tap: function () {
accessorCalled = true;
}
}, function () {
assert.ok(accessorCalled, "It should call the accessor");
});
});
});
bindings.js
define(['knockout','hammer'], function (ko,Hammer) {
return function () {
return {
'init': function (element, valueAccessor) {
var value = valueAccessor();
var hammertime1 = Hammer(element).on("swiperight", function (event) {
$(element).fadeOut('fast', function () {
value();
});
});
}
};
};
});
myviewmodel.js
...
ko.bindingHandlers.tap = new Bindings();
...
You can check my binding collection for how to test
https://github.com/AndersMalmgren/Knockout.Bindings/tree/master/test
This is my function that all my tests using
ko.test = function (tag, binding, test) {
var element = $("<" + tag + "/>");
element.appendTo("body");
ko.applyBindingsToNode(element[0], binding);
var args = {
clean: function () {
element.remove();
}
};
test(element, args);
if (!args.async) {
args.clean();
}
};
edit: Sorry forgot mocking, you just do
$.fn.on = function() {
}
I do not know what exact logic you want to test in that code since there hardly is any, but something like this
http://jsfiddle.net/Akqur/
edit:
May you get confused where i hook up your binding? Its done here
{
tap: function() {
ok(true, "It should call the accessor");
}
}
I tell ko to hook up a "tap" binding and instead of hooking in up to a observable I use a mocking function, when your custom bindnig calls value() from the fadeout function the test assert will fire
edit:
Maybe this approuch makes more sense to you?
http://jsfiddle.net/Akqur/5/
Note that it only works if your code is executed synchronous
edit:
Here i use the third argument of ko.test
http://jsfiddle.net/Akqur/8/

angularjs - testing controller

I am just starting with angular and I wanted to write some simple unit tests for my controllers, here is what I got.
app.js:
'use strict';
// Declare app level module which depends on filters, and services
angular.module('Prototype', ['setsAndCollectionsService']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/dashboard', {templateUrl: 'partials/dashboard.html', controller: 'DashboardController'});
$routeProvider.when('/setsAndCollections', {templateUrl: 'partials/setsAndCollections.html', controller: SetsAndCollectionsController});
$routeProvider.when('/repetition', {templateUrl: 'partials/repetition.html', controller: RepetitionController});
$routeProvider.otherwise({redirectTo: '/dashboard'});
}]);
and controllers.js
'use strict';
/* Controllers */
var myApp = angular.module('Prototype');
myApp.controller('DashboardController', ['$scope', function (scope) {
scope.repeats = 6;
}]);
/*function DashboardController($scope) {
$scope.repeats = 5;
};*/
function SetsAndCollectionsController($scope, $location, collectionsService, repetitionService) {
$scope.id = 3;
$scope.collections = collectionsService.getCollections();
$scope.selectedCollection;
$scope.repetitionService = repetitionService;
$scope.switchCollection = function (collection) {
$scope.selectedCollection = collection;
};
$scope.addCollection = function () {
$scope.collections.push({
name: "collection" + $scope.id,
sets: []
});
++($scope.id);
};
$scope.addSet = function () {
$scope.selectedCollection.sets.push({
name: "set" + $scope.id,
questions: []
});
++($scope.id);
};
$scope.modifyRepetition = function (set) {
if (set.isSelected) {
$scope.repetitionService.removeSet(set);
} else {
$scope.repetitionService.addSet(set);
}
set.isSelected = !set.isSelected;
};
$scope.selectAllSets = function () {
var selectedCollectionSets = $scope.selectedCollection.sets;
for (var set in selectedCollectionSets) {
if (selectedCollectionSets[set].isSelected == false) {
$scope.repetitionService.addSet(set);
}
selectedCollectionSets[set].isSelected = true;
}
};
$scope.deselectAllSets = function () {
var selectedCollectionSets = $scope.selectedCollection.sets;
for (var set in selectedCollectionSets) {
if (selectedCollectionSets[set].isSelected) {
$scope.repetitionService.removeSet(set);
}
selectedCollectionSets[set].isSelected = false;
}
};
$scope.startRepetition = function () {
$location.path("/repetition");
};
}
function RepetitionController($scope, $location, repetitionService) {
$scope.sets = repetitionService.getSets();
$scope.questionsLeft = $scope.sets.length;
$scope.questionsAnswered = 0;
$scope.percentageLeft = ($scope.questionsLeft == 0 ? 100 : 0);
$scope.endRepetition = function () {
$location.path("/setsAndCollections");
};
}
now I am in process of converting global function controllers to ones defined by angular API as you can see by example of DashboardController.
Now in my test:
describe("DashboardController", function () {
var ctrl, scope;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('DashboardController', {$scope: scope});
}));
it("has repeats attribute set to 5", function () {
expect(scope.repeats).toBe(5);
});
});
I am getting
Error: Argument 'DashboardController' is not a function, got undefined
I am wondering then, where is my mistake? If I understand this right, ctrl = $controller('DashboardController', {$scope: scope}); should inject my newly created scope to my DashboardController to populate it with attributes - in this case, repeats.
You need to set up your Prototype module first.
beforeEach(module('Prototype'));
Add that to your test, above the current beforeEach would work.
describe("DashboardController", function () {
var ctrl, scope;
beforeEach(module('Prototype'));
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('DashboardController', {$scope: scope});
}));
it("has repeats attribute set to 5", function () {
expect(scope.repeats).toBe(5);
});
});

How to get data from model provider which calls a webservice

I want to retrieve data from a model provider, but all I am getting got is 'undefined' in my controller.
Here is the code:
Controller:
pdmAtWeb.controller('SearchCtrl', function($scope, ItemModel){
$scope.updateTableFromSearch = function(){
$scope.myData = ItemModel.findAllItems();
console.log($scope.myData);
};});
Provider
pdmAtWeb.provider('ItemModel', function () {
this.defaultEndpoint = '/item';
this.defaultServiceUrl = 'http://localhost:8080/webservice';
this.setDefaultEndpoint = function (newEndpoint) {
this.defaultEndpoint = newEndpoint;
};
this.setDefaultServiceUrl = function (newServiceUrl) {
this.defaultServiceUrl = newServiceUrl;
}
this.$get = function ($http) {
var endpoint = this.endpoint;
var serviceUrl = this.serviceUrl;
var refreshConnection = function () {
// reconnect
}
return{
findAllItems: function () {
$http({method: 'GET', url: serviceUrl + endpoint}).
success(function (data, status, headers, config) {
console.log(data);
return data;
}).
error(function (data, status, headers, config) {
});
}
}
}});
The provider "ItemModel" receives the correct data from the web service. Perhaps this is an async problem, but I'm not sure.
UPDATE
After adding a deferred/promise implementation it works as expected. Here is the final code:
Controller:
pdmAtWeb.controller('SearchCtrl', function($scope, ItemModel){
$scope.updateTableFromSearch = function(){
ItemModel.findAllItems().then(function(data){
console.log(data);
$scope.myData = data;
});
};
});
Provider
pdmAtWeb.provider('ItemModel', function () {
this.defaultEndpoint = '/item';
this.defaultServiceUrl = 'http://localhost:8080/webservice';
this.setDefaultEndpoint = function (newEndpoint) {
this.defaultEndpoint = newEndpoint;
};
this.setDefaultServiceUrl = function (newServiceUrl) {
this.defaultServiceUrl = newServiceUrl;
}
this.$get = function ($http, $q) {
var endpoint = this.defaultEndpoint;
var serviceUrl = this.defaultServiceUrl;
var refreshConnection = function () {
// reconnect
}
return{
findAllItems: function () {
var deferred = $q.defer();
$http({method: 'GET', url: serviceUrl + endpoint}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject();
});
return deferred.promise;
}
}
}
});
You dont need a deferred to accomplish this. Your $http already returns a promise. In your first example, the reason you are getting an undefined is because you are not returning anything. Check your findAllItems . It is not returning anything.
If you do return $http.get(.....) everything should work without using deferred explicitly.
Here is the corrected version :
pdmAtWeb.provider('ItemModel', function () {
this.defaultEndpoint = '/item';
this.defaultServiceUrl = 'http://localhost:8080/webservice';
this.setDefaultEndpoint = function (newEndpoint) {
this.defaultEndpoint = newEndpoint;
};
this.setDefaultServiceUrl = function (newServiceUrl) {
this.defaultServiceUrl = newServiceUrl;
}
this.$get = function ($http) {
var endpoint = this.endpoint;
var serviceUrl = this.serviceUrl;
var refreshConnection = function () {
// reconnect
}
return{
findAllItems: function () {
//NOTE addition of return below.
return $http({method: 'GET', url: serviceUrl + endpoint}).
success(function (data, status, headers, config) {
console.log(data);
//NOTE: YOU SHOULD ALSO return data here for it to work.
return data;
}).
error(function (data, status, headers, config) {
});
}
}
}});