is not a function, when function is right above? - javascript

i often have the problem that i cant reach the Functions of my js classes inside the js class.
I mostly fix it with this. or a bind(this) but why does this not work? its the exact copy the way i do this in another class.
class Page {
// constructor and props
ShowNewJobPopup() {
var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
console.log(data, element);
}
InitializeFilterElements(filterItems) {
filterItems["Control"].Items.push({
Template: function (itemElement) {
itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
this.ShowNewJobPopup(); // how is this not a function
}.bind(this)
});
}
});
return filterItems;
}
}
when im in the dev console. i can write Page.ShowNewJobPopup (Page is the script this is attached to)

The this is actually not from the class Page.
We rewrite your Page class in the below way and you can see the this is referred to the obj.
class Page {
constructor() {}
ShowNewJobPopup() {
var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
console.log(data, element);
}
InitializeFilterElements(filterItems) {
const obj = {
Template: function (itemElement) {
itemElement.append(
'<div id="btnNeuerJob" style="width: 100%; margin-top: 4px;"></div>'
);
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
this.ShowNewJobPopup();
}.bind(this), // this is referred to obj
});
},
};
filterItems["Control"].Items.push(obj);
return filterItems;
}
}
What you can do is create a variable self to store the this and use it to reference to the class Page later.
class Page {
constructor() {}
ShowNewJobPopup() {
var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
console.log(data, element);
}
InitializeFilterElements(filterItems) {
const self = this; // this here is referred to the class Page
const obj = {
Template: function (itemElement) {
itemElement.append(
'<div id="btnNeuerJob" style="width: 100%; margin-top: 4px;"></div>'
);
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
self.ShowNewJobPopup(); // self is referred to Page Class
},
});
},
};
filterItems["Control"].Items.push(obj);
return filterItems;
}
}

You seem to have several functions with different this contexts nested within each other. It would be much simpler just to create a variable at the top of your class method rather than worrying about passing the right context to each function.
InitializeFilterElements(filterItems) {
const thisPage = this; // SET THE VARIABLE
filterItems["Control"].Items.push({
Template: function (itemElement) {
itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
thisPage.ShowNewJobPopup();
}
});
}
});
return filterItems;
}

The value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called.
InitializeFilterElements(filterItems) {
const self = this; // self now holds the value of this reference
filterItems["Control"].Items.push({
Template: function (itemElement) {
itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
self.ShowNewJobPopup();
}
});
}
});
return filterItems;
}

This is a classic problem of this in JavaScript. When the Template function is invoked, the reference of this changes to whatever the context of the object, in which the function is invoked.
Checkout the example for the error
A possible fix is
class Page {
// constructor and props
ShowNewJobPopup() {
var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
console.log(data, element);
}
InitializeFilterElements(filterItems) {
var that = this;
filterItems["Control"].Items.push({
Template: function (itemElement) {
itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
$("#btnNeuerJob").dxButton({
type: "default",
text: "Neuer Job",
disabled: false,
onClick: function () {
this.ShowNewJobPopup(); // how is this not a function
}.bind(that)
});
}
});
return filterItems;
}
}
class A {
test() {
console.log("test")
}
test2() {
let a = []
a.push({
template() {
function abc() {
console.log(this)
this.test()
}
abc.bind(this)()
}
})
return a
}
}
let a = new A()
let arr = a.test2()
//this will work
arr[0].template.bind(a)()
console.log("===========")
arr[0].template()

Related

Backbone subview is not rendered, "Uncaught ReferenceError: view is not defined" error returned

I am working on a site that uses Backbone.js, jQuery and I am trying to render a subview that has to display a description of the current page, loaded depending on a choice made from a dropdown menu. I searched for more info in the web but I am still stuck on this. Please help!
Here is the main view in which I have to load the description view:
const InquiryContentView = Backbone.View.extend(
{
el: $('#inquiryContent'),
events: {
'change #styles': 'renderTabs',
'click li.tab': 'renderTabPanel'
},
initialize: function () {
const view = this
this.inquiryContent = new InquiryContent
this.inquiryContent.fetch(
{
success: function () {
view.listenTo(view.inquiryContent, 'update', view.render)
view.render()
}
})
},
render: function () {
const data = []
this.inquiryContent.each(function (model) {
const value = {}
value.id = model.id
value.text = model.id
value.disabled = !model.get('active')
data.push(value)
})
data.unshift({id: 'none', text: 'Select One', disabled: true, selected: true})
this.$el.append('<h2 class="pageHeader">Inquiry Content</h2>')
this.$el.append('<select id="styles"></select>')
this.$stylesDropdown = $('#styles')
this.$stylesDropdown.select2(
{
data: data,
dropdownAutoWidth: true,
width: 'element',
minimumResultsForSearch: 10
}
)
this.$el.append('<div id="navWrapper"></div>')
this.$el.append('<div id="tNavigation"></div>')
this.$navWrapper = $('#navWrapper')
this.$tNavigation = $('#tNavigation')
this.$navWrapper.append(this.$tNavigation)
this.$el.append('<div id="editorDescription"></div>')
},
renderTabs: function (id) {
const style = this.inquiryContent.findWhere({id: id.currentTarget.value})
if (this.clearTabPanel()) {
this.clearTabs()
this.tabsView = new TabsView({style: style})
this.$tNavigation.append(this.tabsView.el)
}
},
renderTabPanel (e) {
const tabModel = this.tabsView.tabClicked(e.currentTarget.id)
if (tabModel && this.clearTabPanel()) {
this.tabPanel = new TabPanelView({model: tabModel})
this.$tNavigation.append(this.tabPanel.render().el)
}
},
clearTabs: function () {
if (this.tabsView !== undefined && this.tabsView !== null) {
this.tabsView.remove()
}
},
clearTabPanel: function () {
if (this.tabPanel !== undefined && this.tabPanel !== null) {
if (this.tabPanel.dataEditor !== undefined && this.tabPanel.dataEditor.unsavedChanges) {
if (!confirm('You have unsaved changes that will be lost if you leave the page. '
+ 'Are you sure you want to leave the page without saving your changes?')) {
return false
}
this.tabPanel.dataEditor.unsavedChanges = false
}
this.tabPanel.remove()
}
return true
}
}
)
I am trying to render the subview adding this method:
renderDescription () {
this.$editorDescription = $('#editorDescription')
this.descView = new DescView({model: this.model})
this.$editorDescription.append(this.descView)
this.$editorDescription.html(DescView.render().el)
}
It has to be rendered in a div element with id='editorDescription'
but I receive Uncaught ReferenceError: DescView is not defined
Here is how DescView is implemented:
window.DescView = Backbone.View.extend(
{
el: $('#editorDescription'),
initialize: function () {
_.bindAll(this, 'render')
this.render()
},
render: function () {
$('#editorDescriptionTemplate').tmpl(
{
description: this.model.get('description')})
.appendTo(this.el)
}
);
What am I doing wrong?
Your implementation of the DescView is incomplete. You are missing a bunch of closing braces and brackets. That's why it's undefined.

Changing state of component data from sibling component Vue.JS 2.0

Given:
<parent-element>
<sibling-a></sibling-a>
<sibling-b></sibling-b>
</parent-element>
How can I get access to a click event on a button in siblingA to change some value to another in sibling-b using $emit(…)?
#craig_h is correct, or you can use $refs like:
<parent-element>
<sibling-a #onClickButton="changeCall"></sibling-a>
<sibling-b ref="b"></sibling-b>
</parent-element>
In parent methods:
methods: {
changeCall() {
this.$refs.b.dataChange = 'changed';
}
}
In siblingA:
Vue.component('sibling-a', {
template: `<div><button #click="clickMe">Click Me</button></div>`,
methods: {
clickMe() {
this.$emit('onClickButton');
}
}
});
In siblingB:
Vue.component('sibling-b', {
template: `<div>{{dataChange}}</div>`,
data() {
return {
dataChange: 'no change'
}
}
});
For that you can simply use a global bus and emit your events on to that:
var bus = new Vue();
Vue.component('comp-a', {
template: `<div><button #click="emitFoo">Click Me</button></div>`,
methods: {
emitFoo() {
bus.$emit('foo');
}
}
});
Vue.component('comp-b', {
template: `<div>{{msg}}</div>`,
created() {
bus.$on('foo', () => {
this.msg = "Got Foo!";
})
},
data() {
return {
msg: 'comp-b'
}
}
});
Here's the JSFiddle: https://jsfiddle.net/6ekomf2c/
If you need to do anything more complicated then you should look at Vuex

Vue JS Custom directive data binding

I'm creating a custom directive to make a form submit via ajax - however I can't seem to get validation errors to bind to the Vue instance.
I am adding my directive here:
<form action="{{ route('user.settings.update.security', [$user->uuid]) }}" method="POST"
enctype="multipart/form-data" v-ajax errors="formErrors.security" data="formData.security">
My directive looks like:
Vue.directive('ajax', {
twoWay: true,
params: ['errors', 'data'],
bind: function () {
this.el.addEventListener('submit', this.onSubmit.bind(this));
},
update: function (value) {
},
onSubmit: function (e) {
e.preventDefault();
this.vm
.$http[this.getRequestType()](this.el.action, vm[this.params.data])
.then(this.onComplete.bind(this))
.catch(this.onError.bind(this));
},
onComplete: function () {
swal({
title: 'Success!',
text: this.params.success,
type: 'success',
confirmButtonText: 'Back'
});
},
onError: function (response) {
swal({
title: 'Error!',
text: response.data.message,
type: 'error',
confirmButtonText: 'Back'
});
this.set(this.vm, this.params.errors, response.data);
},
getRequestType: function () {
var method = this.el.querySelector('input[name="_method"]');
return (method ? method.value : this.el.method).toLowerCase();
},
});
And my VUE instance looks like:
var vm = new Vue({
el: '#settings',
data: function () {
return {
active: 'profile',
updatedSettings: getSharedData('updated'),
formData: {
security: {
current_password: ''
}
},
formErrors: {
security: []
},
}
},
methods: {
setActive: function (name) {
this.active = name;
},
isActive: function (name) {
if (this.active == name) {
return true;
} else {
return false;
}
},
hasError: function (item, array, sub) {
if (this[array][sub][item]) {
return true;
} else {
return false;
}
},
isInArray: function (value, array) {
return array.indexOf(value) > -1;
},
showNotification: function () {
if (this.updatedSettings) {
$.iGrowl({
title: 'Updated',
message: 'Your settings have been updated successfully.',
type: 'success',
});
}
},
}
});
However, when I output the data, the value for formErrors.security is empty
Any idea why?
The issue is with the this.set(/* ... */) line. this.set doesn't work the same as Vue.set or vm.$set.
this.set attempts to set the path that you passed to the directive: v-my-directive="a.b.c". So running this.set('foo') will attempt to set $vm.a.b.c to 'foo'.
What you want to do is this:
(ES6)
this.params.errors.splice(0, this.params.errors.length, ...response.data)
(Vanilla JS)
this.params.errors.splice.apply(this.params.errors, [0,this.params.errors.length].concat(response.data))
That will update whatever Object is tied to the errors param on the DOM Node. Make sure that you do v-bind:errors="formErrors.security" or :errors="formErrors.security".

Cannot set property 'new_form' of undefined

I'm having trouble with a Backbone.js tutorial from Treehouse. Here's my code:
var NotesApp = (function () {
var App = {
stores: {}
}
App.stores.notes = new Store('notes');
// Note Model
var Note = Backbone.Model.extend({
//Local Storage
localStorage: App.stores.notes,
initialize: function () {
if (!this.get('title')) {
this.set({
title: "Note at " + Date()
})
};
if (!this.get('body')) {
this.set({
body: "No Body"
})
};
}
})
//Views
var NewFormView = Backbone.View.extend({
events: {
"submit form": "createNote"
},
createNote: function (e) {
var attrs = this.getAttributes(),
note = new Note();
note.set(attrs);
note.save();
},
getAttributes: function () {
return {
title: this.$('form [name=title]').val(),
body: this.$('form [name=body]').val()
}
}
});
window.Note = Note;
$(document).ready(function () {
App.views.new_form = new NewFormView({
el: $('#new')
});
})
return App
})();
And I get the error: Cannot set property 'new_form' of undefined
I've tried to go back and copy the code as close as possible, but I still couldn't get it to work. Any suggestions?
After stores: {} add ,
views: {}.
You need an object to attach your view to - JavaScript has no vivification

Load method of Ext.data.store - how to delay a return statement AND a function call until the data is loaded?

connectLoadRenderStoreAndGetCheckBox: function () {
this.someStore = new Ext.data.Store({
proxy:
reader:
]),
sortInfo: { field: , direction: }
});
this.someStore.load(
{
params:
{
}
});
//I left out parameters; lets assume they are valid and work.
this.someStore.on("load", this._renderColumns, this);
return ([this._getCheckBox()]);
}
On 'load' I want to both execute the function this._renderColumns (which uses the data from the server) and also return a checkbox (which also uses data from the server).
What is a quick & easy way to only return the checkbox after the data is loaded?
_getCheckBox: function () {
if (UseDefault == "y") {
return new Ext.form.Checkbox(
{
fieldLabel:,
itemCls:,
checked: true,
labelStyle:
});
}
else {
return new Ext.form.Checkbox(
{
fieldLabel:,
itemCls:,
checked: false,
labelStyle:
});
}
},
_renderColumns: function () {
var record2 = this.something.something2(2);
UseDefault = record2.get("UseDefault");
}

Categories

Resources