I am new to AngularJs. Currently I have a directive that populates a JavaScript object called keyListeners. Now this object gets populated and serves its purpose fine the first time I come to the page on which it is used. Unfortunately when I navigate away from the page and then come back to it I see errors in my console like
"angular.min.js:116 More than one amtAltKey found for key 'A' "
Then the functionality of the page starts to break.
I know I could theoretically check for the existence of the element in keyListeners, before adding it to the object. However, instead of doing that I would like to run some logic to clear out keyListeners on control change. My directive that actually populates keyListeners is below. How can I clear this out every time the controller/page changes.
app.directive("amtAltKey", function () {
return {
link: function (scope, elem, attrs) {
var altKey = attrs.amtAltKey.toUpperCase();
if(keyListeners[altKey] !== undefined) { throw 'More than one amtAltKey found for key \''+ altKey + '\''; }
if (altKey === '') { throw "Alt Key value key must be given"; }
var el = elem[0];
if (!el.hasChildNodes()) { throw 'amtAltKey element must have child text'; }
if(el.firstChild.nodeName !== '#text') { throw 'amtAltKey element\'s child must be text'; }
var text = el.innerText;
var textUpper = text.toUpperCase();
var indexOfKey = textUpper.indexOf(altKey);
if (indexOfKey === -1) { throw 'amtAltKey for \'' + altKey + '\' was not found in element\s text; ' + text; }
var newText = text.replace(new RegExp(attrs.amtAltKey), '<u>' + attrs.amtAltKey + '</u>');
el.innerHTML = newText;
keyListeners[altKey] = el;
}
};
});
Is keyListeners currently a global? If so, that's the problem. It's not being garbage collected when the directive is blown up, when switching screens. Just add do something like...
var keyListenteners = {};
...in your directive.
Or, better, move keyListeners in to their own service or factory and include it. Something like:
angular.module("myApp").factory("keyListeners", function() {
return {
// your properties here
};
});
This will act like a data singleton, kind of like your global, between your different controllers. A change made to one will be reflected in the others. That of course is the very problem you want to avoid, so you could add a clear() method to this singleton and call it every time your route changes or even in your controller constructor.
Related
I have an Umbraco plugin that is literally a vanilla .js file that allows me to retrieve some JSON from a service, then it fills in some of the fields on the current page, e.g by doing:
var setTxt = function(id, val) {
var txt = document.getElementById(id);
if (txt && val != null && val != undefined) {
return txt.value = val;
};
};
However, when I hit save, the angular model doesn't save any of the changes to the inputs - probably because no change detection has been triggered.
I've tried e.g with the field 'publisher':
angular.element(document.querySelector("#publisher")).scope().apply()
but I get the error:
VM94421:95 TypeError: Cannot read property 'apply' of undefined
I really don't want to get stuck into angular 1, my vanilla js is all working, I just need to get umbraco to scoop up all the values that I've set on the various fields.
Q) How can I force this?
p.s. - please don't comment that this is bad practice, I just need to get this job done.
EDIT by question poster:
Turns out as jQuery Lite is included already, you can just call:
$('#' + id).trigger('input');
Original answer below also works:
You should trigger "input" event to let angular know your changes:
var setTxt = function(id, val) {
var txt = document.getElementById(id);
if (txt && val != null && val != undefined) {
txt.value = val;
raiseEvent(txt, 'input');
return val;
};
};
var raiseEvent = function(el, eventType) {
var event = document.createEvent('Event');
event.initEvent(eventType, true, true);
el.dispatchEvent(event);
};
BTW, $scope doesn't have "apply" function. Its name is "$apply". Also as far I understand "scope.$appy(cb)" will pick up changes that are applied to the scope variable, in your case you manipulate directly with dom element.
Debug Data must be enabled enabled, in order for functionality to call angular.element(yourElement).scope() to work. It looks like its enabled by default.
I'm trying to use Knockout to make the usage for an infinite scroll plugin I am using a bit nicer, but struggling with how to bind it. Not sure if it's even possible in the current form.
The scroller calls a data function which loads the next block of data via AJAX. It then calls a factory function that converts that data into HTML, and it then loads the HTML into the container, and updates its internal state for the current content size.
I'm stuck on the fact that it expects an HTML string.
What I want to do is this:
<div class="scroller" data-bind="infiniteScroll: { get: loadItems }">
<div class="item">
<p>
<span data-bind="text:page"></span>
<span class="info" data-bind="text"></span>
</p>
</div>
</div>
And my binding, which I'm completely stuck on, is this - which is currently just hardcoding the response, obviously - that's the bit I need to replace with the template binding:
ko.bindingHandlers.infiniteScroll = {
init:
function(el, f_valueaccessor, allbindings, viewmodel, bindingcontext)
{
if($.fn.infiniteScroll)
{
// Get current value of supplied value
var field = f_valueaccessor();
var val = ko.unwrap(field);
var options = {};
if(typeof(val.get) == 'function')
options = val;
else
options.get = val;
options.elementFactory = options.elementFactory ||
function(contentdata, obj, config)
{
var s = '';
for(var i = 0; i < contentdata.length; i++)
{
var o = contentdata[i];
// NEED TO REPLACE THIS
s += '<div class="item"><p>Item ' + o.page + '.' + i + ' <span class="info">' + o.text + '</span></p></div>';
}
return s;
};
$(el).infiniteScroll(options);
return { controlsDescendantBindings: true };
}
}
};
contentdata is an array of objects e.g. [ { page:1, text:'Item1' }, { page:1, text:'Item2' } ... ]
Page sizes may differ between calls; I have no way of knowing what the service will return; it is not a traditional page, think of it more as the next block of data.
So in the element factory I want to somehow bind the contentdata array using the markup in .scroller as a template, similar to foreach, then return that markup to the scroller plugin.
Note that I can modify the infinite scroller source, so if if can't be done with strings, returning DOM elements would also be fine.
I just can't get how to a) use the content as a template, and b) return the binding results to the plugin so it can update its state.
NOTE: The page I eventually intend to use this is currently using a foreach over a non-trivial object model; thus the need to use the same markup; it needs to be pretty much a drop in replacement.
I have actually found out how to do it using the existing scroller following this question: Jquery knockout: Render template in-memory
Basically, you use applyBindingsToNode(domelement, bindings), which will apply KO bindings to a nodeset, which importantly does not have to be connected to the DOM.
So I can store the markup from my bound element as the template, then empty it, then for the element factory, create a temporary node set using jQuery, bind it using the above function, then return the HTML.
Admittedly, this would probably be better off refactored to use a pure KO scroller, but this means I can continue to use the tested and familiar plugin, and the code might help people as this seems to be quite a common question theme.
Here is the new code for the binding (markup is as above).
ko.bindingHandlers.infiniteScroll = {
init:
function(el, f_valueaccessor, allbindings, viewmodel, bindingcontext)
{
if($.fn.infiniteScroll)
{
// Get current value of supplied value
var field = f_valueaccessor();
var val = ko.unwrap(field);
var options = {};
if(typeof(val.get) == 'function')
options = val;
else
options.get = val;
var template = $(el).html();
options.elementFactory = options.elementFactory ||
function(contentdata, obj, config)
{
// Need a root element for foreach to use as a container, as it removes the root element on binding.
var newnodes = $('<div>' + template + '</div>');
ko.applyBindingsToNode(newnodes[0], { foreach: contentdata });
return newnodes.html();
};
$(el)
.empty()
.infiniteScroll(options);
return { controlsDescendantBindings: true };
}
}
};
I am using breeze to communicate with Web.API 2.1
In my backend I save some values as a list of strings (instead of saving one-to-many relations). In the front end I want to break these values, edit them, put them back together and persist them to the DB.
emailsString is the actual property that is persisted to the DB and exists in the model.
fullName acts as an "interface" to reading and modifying the first and last name properties.
I have the following:
function registerUserProfile(metadataStore) {
metadataStore.registerEntityTypeCtor('UserProfile', profile, profileInitializer);
function profile() {
this.fullName = '';
this.emails = [];
}
function profileInitializer(newItem) {
if (!newItem.emailsString || newItem.emailsString.length === 0) newItem.emails = [{ email: '' }];
}
Object.defineProperty(profile.prototype, 'fullName', {
get: function() {
var fn = this.firstName;
var ln = this.lastName;
return ln ? fn + ' ' + ln : fn;
},
set: function (value) {
var parts = value.split(' ');
this.firstName = parts.shift();
this.lastName = parts.shift() || '';
}
});
Object.defineProperty(profile.prototype, 'emailsString', {
get: function () {
return objectToStringArray(this.emails, 'email');
},
set: function (value) {
this.emails = stringToObjArray(value, 'email');
}
});
function objectToStringArray(objectArray, objectValueKey) {
var retVal = '';
angular.forEach(objectArray, function (obj) {
retVal += obj[objectValueKey] + ';';
});
if (retVal.length > 0)
retVal = retVal.substring(0, retVal.length - 1); //remove last ;
return retVal;
}
function stringToObjArray(stringArray, objectValueKey) {
var objArray = [];
angular.forEach(stringArray.split(';'), function (str) {
var item = {};
item[objectValueKey] = str;
objArray.push(item);
});
return objArray;
}
If I modify the emailString value and call saveChanges on breeze nothing happens. If I modify the fullName property ALL changes are detected and saveChanges sends the correct JSON object for saving (including emailString value).
From what I understand, overriding the emailString property I somehow break the change tracking for this property. fullName is not a mapped property and thus is not overriding anything so it works. Am I going the correct way? If so is there a way to notify breeze that the overriden property has changed?
In general, Breeze takes over each property on an object and insures that internally it is informed about any changes to each property. How this is done is different depending on whether you are using Angular, Knockout or Backbone ( or a custom modelLibrary adapter).
But if you plan on modifying the property yourself to do something similar you need to insure that breeze is still getting notified.
Based on your posted code I'm assuming that you are using Angular. In that case you first need to determine whether your code is getting executed before or after Breeze's code.
My guess is that if you make your changes early enough then Breeze will be able to wrap them successfully. However, if your changes occur after Breeze's then you need to insure that Breeze's code is invoked as well. Debugging into the source for this is probably your best bet. And the Breeze Angular adapter is a good source as a example of how to wrap a property that might already be wrapped with another defineProperty.
Take a look at the snippet below. Is there any function I could write in replace of ... to generate the route, that could reused in another function? Something like var route = this.show.fullyQualifiedName perhaps?
var services = {
'github.com': {
api: {
v2: {
json: {
repos: {
show: function(username, fn) {
var route = ...;
// route now == 'github.com/api/v2/json/repos/show'
route += '/' + username;
return $.getJSON('http://' + route).done(fn);
}
}
}
}
}
}
}
No, there isn't, at least not using "reflection" style operations.
Objects have no knowledge of the name of the objects in which they're contained, not least because the same object (reference) could be contained within many objects.
The only way you could do it would be to start at the top object and work your way inwards, e.g.:
function fillRoutes(obj) {
var route = obj._route || '';
for (var key in obj) {
if (key === '_route') continue;
var next = obj[key];
next._route = route + '/' + key;
fillRoutes(next);
}
}
which will put a new _route property in each object that contains that object's path.
See http://jsfiddle.net/alnitak/WbMfW/
You can't do a recursive search, like Alnitak said, but you could do a top-down search, although it could be somewhat slow depending on the size of your object. You'd loop through the object's properties, checking to see if it has children. If it does have a child, loop through that, etc. When you reach the end of a chain and you haven't found your function, move to the next child and continue the search.
Don't have the time to write up an example now, but hopefully you can piece something together from this.
Imagine a simple backbone model like
window.model= Backbone.Model.extend({
defaults:{
name: "",
date: new Date().valueOf()
}
})
I'm trying to find a way to always make the model store the name in lower-case irrespective of input provided. i.e.,
model.set({name: "AbCd"})
model.get("name") // prints "AbCd" = current behavior
model.get("name") // print "abcd" = required behavior
What's the best way of doing this? Here's all I could think of:
Override the "set" method
Use a "SantizedModel" which listens for changes on this base model and stores the sanitized inputs. All view code would then be passed this sanitized model instead.
The specific "to lower case" example I mentioned may technically be better handled by the view while retrieving it, but imagine a different case where, say, user enters values in Pounds and I only want to store values in $s in my database. There may also be different views for the same model and I don't want to have to do a "toLowerCase" everywhere its being used.
Thoughts?
UPDATE: you can use the plug-in: https://github.com/berzniz/backbone.getters.setters
You can override the set method like this (add it to your models):
set: function(key, value, options) {
// Normalize the key-value into an object
if (_.isObject(key) || key == null) {
attrs = key;
options = value;
} else {
attrs = {};
attrs[key] = value;
}
// Go over all the set attributes and make your changes
for (attr in attrs) {
if (attr == 'name') {
attrs['name'] = attrs['name'].toLowerCase();
}
}
return Backbone.Model.prototype.set.call(this, attrs, options);
}
It would be a hack, because this isn't what it was made for, but you could always use a validator for this:
window.model= Backbone.Model.extend({
validate: function(attrs) {
if(attrs.name) {
attrs.name = attrs.name.toLowerCase()
}
return true;
}
})
The validate function will get called (as long as the silent option isn't set) before the value is set in the model, so it gives you a chance to mutate the data before it gets really set.
Not to toot my own horn, but I created a Backbone model with "Computed" properties to get around this. In other words
var bm = Backbone.Model.extend({
defaults: {
fullName: function(){return this.firstName + " " + this.lastName},
lowerCaseName: function(){
//Should probably belong in the view
return this.firstName.toLowerCase();
}
}
})
You also listen for changes on computed properties and pretty much just treat this as a regular one.
The plugin Bereznitskey mentioned is also a valid approach.