Why is 'this' losing context in new Angular 1.5 components? - javascript

Got a very odd issue coming up here with the new components. When we had a 1.4 directive we had the following code...
(function () {
'use strict';
angular.module('app.board').directive('dcCb', dcClipboardCopy);
function dcCb() {
return {
link : function(scope, elem) {
var clipboard = new Clipboard(elem[0]);
elem.on('$destroy', function() {
clipboard.destroy();
});
}
};
}
})();
Inside the clipboard.destroy() function is the following...
Clipboard.prototype.destroy = function(){
this.listeners.destroy();
}
In 1.4 this is the same as the element so...
<button class="btn btn-sm btn-menu-outline copy-button" ...
So this worked fine as the button element seemed to have the listeners property which could be invoked.
However after the upgrade to 1.5 and now we have a component like this....
(function() {
'use strict';
angular.module('app.board').component('dcCb', {
...
controller: [ '$element','$scope',function($element,$scope) {
var self = this;
self.$postLink = postLink;
function postLink(){
var clipboard = new Clipboard($element[0]);
...
$element.on('$destroy', clipboard.destroy);
}
}]
});
})();
this (when inside the destroy function of the Clipboard) is now the controller object. So trying to call this.listeners throws an error.
First Question :
I understand that this in new components is the component scope but in 1.4 it was the button element. Surely in both the button element should be $element? Were we doing something wrong in 1.4?
Second Question :
Shouldn't var clipboard = new Clipboard($element[0]) force the context of this inside the clipboard to always be the clipboard itself (due to the new keyword)?

You're handing a function, which is arbitrarily defined on a class, off to the window and event listeners to be executed in a different context than the instance of Clipboard:
$element.on('$destroy', clipboard.destroy);
This is a fundamental concept of execution context in javascript, and I'd recommend reading up on it. But you can easily solve your current problem by simply binding the context of the function you are passing:
$element.on('$destroy', clipboard.destroy.bind(clipboard));

Related

jQuery this context to point to the element in context

I have a situation using BS3 modal events and my app functionality is wrapped in object with exposed methods (reveal module pattern). I have event received from BS and I what my $this to point to the Event object instead of the App object.
I tried jquery this context with the jQuery proxy, which seems to be the best thing, but for some reason the things didn't worked for me
var globalAppDef = (function() {
function modalFilters() {
$('#filtersMore')
.on('show.bs.modal', (event) => {
const sourceElement = $(event.relatedTarget);
$(sourceElement.data().filters).removeClass('hidden');
})
/*
* Transfer the proper #this of the event outside the {globalAppDef} Object
*/
.on('hidden.bs.modal', $.proxy((event) => {
$(this).find(".form-list-items-1").addClass('hidden');
$(this).find(".form-list-items-1").addClass('hidden');
}, this));
}
return modalFilters: modalFilters
}
});
var globalApp = new globalAppDef();
globalApp.initialize();
$(document).ready(function () {globalApp.modalFilters()});
What I what to achieve is on the second hidden.bs.modal $this to point to my Modal, which is $('#filtersMore') element.
actually it it was the Arrow function the reason for that this stayed in the Object context.
That way worked:
.on('hidden.bs.modal', $.proxy(function (event) {
$(this).find(".form-list-items-1, .form-list-items-2").addClass('hidden');
}, $('#filtersMore')));

Why my applyBindings doesn't work? Knockout

Hello I am trying simply to create input and iframe and when I paste the YouTube link the iframe should change with the new src. I have done this so far
<div class="heading">id <input data-bind="text: youtubeLink"/></div>
<iframe id="player" type="text/html" width="444" height="250" frameborder="0" data-bind="attr: { src: linkEmbed }"></iframe>
And in the script:
function MyViewModel() {
this.youtubeLink = ko.observable('https://www.youtube.com/watch?v=4UNkmlCKw9M');
this.linkEmbed = ko.pureComputed({
read: function () {
var extract = this.youtubeLink().replace("/watch?v=", "/embed/");
console.log(extract)
return extract;
},
write: function (value) {
this.youtubeLink();
},
owner: this
});
}
ko.applyBindings(MyViewModel());
This works exactly as I want but the video wont change if I paste another link in the input.
I am using this from knockout documentation: http://knockoutjs.com/documentation/computed-writable.html
You have several problems:
You don't call new on your model, but you wrote it as a constructor
You use text binding instead of value binding for your input
Your computed's write doesn't assign, but you don't need it anyway
Once you correct those, it works.
function MyViewModel() {
var model = {};
model.youtubeLink = ko.observable('https://www.youtube.com/watch?v=4UNkmlCKw9M');
model.linkEmbed = ko.pureComputed(function () {
var result = model.youtubeLink().replace("/watch?v=", "/embed/")
return result;
});
return model;
}
ko.applyBindings(MyViewModel());
http://jsfiddle.net/ueoob7ne/2/
TLDR: jQuery hides knockout bind errors.
Another thing that breaks it....
jQuery is known to catch exceptions and hide them. I had to step through knockout-debug.js AND THEN jquery.js until i got to a part that looks like this (around line 3600)
// Only normal processors (resolve) catch and reject exceptions
process = special ?
mightThrow :
function() {
try {
mightThrow();
} catch ( e ) {
wouldn't you know it... I put a watch on (e) an here was what I found hidden in there:
Error: Unable to process binding "text: function(){return ko.toJSON(vm.model(),null,2) }"
Message: Multiple bindings (if and text) are trying to control descendant bindings of the same element

AngularJS - Shared service object being deleted incorrectly

When I trigger deleteQuestion() a second time 2 questions get deleted. Any idea? Let me know if you need to see more of my code.
controller.js
crtPromoCtrl.controller('surveyCtrl', ['$scope', 'surveySrv', function($scope, surveySrv)
{
$scope.questions = surveySrv.getQuestions();
$scope.editQuestion = function(index)
{
surveySrv.setEditQuestion(index);
};
$scope.deleteQuestion = function(index)
{
$(document).off('click', '#confirmationModal #confirm');
$('#confirmationModal').modal('show');
$(document).on('click', '#confirmationModal #confirm', function()
{
surveySrv.deleteQuestion(index);
$scope.$apply();
});
};
}]);
service.js
crtPromoSrv.service('surveySrv', function()
{
var questions = [];
var editQuestion;
this.getQuestions = function()
{
return questions;
};
this.addQuestion = function(question)
{
questions.push(question);
};
this.setEditQuestion = function(index)
{
editQuestion = questions[index];
};
this.getEditQuestion = function()
{
return editQuestion;
};
this.clearEditQuestion = function()
{
editQuestion = undefined;
};
this.deleteQuestion = function(index)
{
questions.splice(index, 1);
console.log(questions);
};
});
EDIT: I'm thinking it's an event propagation thing, since when I have 5 q's it deletes #2 and #3 when I delete #2.
EDIT: Fixed, see controller.js code.
It appears you are adding the 'click' function to your #confirmationModal #confirm button multiple times. The first time $scope.deleteQuestion is called, it adds the function. The second time you call it, it adds it again so when it is clicked, the function is called twice.
A simple fix would be to unbind the 'click' event before adding it again. Something like this: $('#confirmationModal #confirm').off('click');
The better solution here is to not use jQuery at all for these event bindings. Using a simple Angular modal directive (like the one provided in the Angular-UI library, for instance) would be the correct way to do this. Then you can just have an ng-click on the button and never have this problem.

AngularJS return value in the scope from an addEventListener

I have an AngularApp in an iframe and I have a controller with this code to get a click event from the iframe container (main window):
$window.addEventListener('message', function(e) {
$scope.$apply(function() {
console.log(e.data.url); // http://<something>
$scope.widget.pageUrl = e.data.url;
});
});
console.log($scope.widget.pageUrl); // undefined
Everything works fine except I cannot get the $scope.widget.pageUrl variable filled. It remains undefined outside the $window.addEventListener.
Any hint?
This should also work:
$window.addEventListener('message', function (e) {
console.log(e.data.url); // http://<something>
$scope.widget.pageUrl = e.data.url;
$scope.$apply();
});
console.log($scope.widget.pageUrl);
Yaa that's because javascript have function level scoping which means that you need to pass e into the function that you supply to the $scope.$apply otherwise this function will not have event object.
doing this should help.
$scope.$apply(function(e) {
console.log(e.data.url);
$scope.widget.pageUrl = e.data.url;
});
I have not tested it though.

durandaljs - how to query a DOM element from a widget after ready

I want to query a element in a durandaljs widget, when it's ready.
If i use the selector directly in the data-binding, the element will not be found:
html (no attached view):
<button id="myButton"></button>
<div data-bind="widget: { kind: 'myWidget', options: { btn: $('#myButton') } }"></div>
controller.js:
define(function (require) {
var ctor = function (element, settings) {
var btn = settings.options.btn;
// btn = $('#myButton'); // this will work, but i'm not sure if the DOM is
// currently ready in the constructor
btn.on("click", function () {
console.log("I want to be fired");
});
};
return ctor;
});
Whats the best way to query a DOM element from a durandal widget at start?
I'm not sure where the html fragment belongs to so there are two slightly different answers.
First I'd suggest that you don't pass in the btnas jQuery object ({btn: $('myButton')}) , when you're not sure that it already exists. It's probably better to pass in a selector {btn: '#myButton'} and let the widget figure out how to deal with it.
Does your widget have its own view.html and the button is defined inside? If that's the case than you should take a look at the viewAttached callback.
var ctor = function (element, settings) {
this.btn = settings.options.btn;
};
ctor.prototype.viewAttached = function (view){
var btn = $(this.btn, view);
if ( btn.length > 0 ) {
btn.on("click", function () {
console.log("I want to be fired");
});
}
}
If your widget doesn't have its own view.html than you should let the widget know by adding a view property to the settings object with a value of false.
Here's the paragraph from http://durandaljs.com/documentation/Creating-A-Widget/ that explains that.
Note: In some cases, your widget may not actually need a view. Perhaps it's just adding some jQuery behavior or applying an existing jQuery plugin to a dom element. To tell Durandal that there is no view to load and bind, add a view property to the settings object with a value of false inside your widget's constructor.
In that instance however you can only access elements that are already in the DOM when the widget is instantiated e.g.
var ctor = function (element, settings) {
settings.view = false;
this.btn = $(settings.options.btn);
if ( this.btn.length > 0 ) {
this.btn.on("click", function () {
console.log("I want to be fired");
});
}
};

Categories