dojo on.js TypeError matchesTarget is undefined - dojo

I'm working to extend some legacy dojo code (v1.8). I added a button which when clicked calls a simple handle function. The problem is, nothing happens when I click the button and I get the following error in Firebug:
TypeError: matchesTarget is undefined
Everthing worked before, and I only added the following code:
require(["dojo/on"], function (on) {
on(document.getElementById("submitBtn"), "button:click", function (e) {
onSubmitQuery();
});
});
onSubmitQuery:function () {
var model_type_uuid = document.getElementById("modelTypeSelect").get('value');
// check to see if model_type_uuid is not undefined before submitting
if (model_type_uuid === undefined || model_type_uuid == "00000000-0000-0000-0000-000000000000") {
alert('Invalid Decision Model Type ' + model_type_uuid + ' for Decision Query submission');
return;
}
if (document.getElementByID("modeSelector").get('value') == "simulate") {
submitStandingQuery(model_type_uuid);
} else {
submitInteractiveQuery(model_type_uuid);
}
}
I've been pulling my hair out trying to figure this out. Please help!

You need to add the dojo/query module in order to match the selector button within its parent node submitBtn.
require(["dojo/on", "dojo/query"], function (on) {
on(document.getElementById("submitBtn"), "button:click", function (e) {
onSubmitQuery();
});
});

Related

Incomprehensible "Uncaught TypeError: Cannot read property 'removeChild' of null" error

In my app, clicking a certain button changes its caption to a different one, and clicking it again changes it back to the default caption.
When clicking it I get this error message:
Uncaught TypeError: Cannot read property 'removeChild' of null
This doesn't make sense to me because there's no DOM manipulation here. I simplified my code as much as possible while keeping the error:
data () {
return {
ctaCaptions: [
'see case studies',
'hide case studies'
],
ctaCaption: ''
}
},
methods: {
handleClick () {
this.ctaCaption = this.ctaCaptions[1]
}
}
HTML:
<a
#click="handleClick"
v-html="ctaCaption"
/>
Any suggestion as to what causes this error?
methods: {
handleClick () {
this.ctaCaption = this.ctaCaptions[1]
}
}
Inside event handlers, this points to the event.target (in your case the HTMLButtonElement).
In your case, you want a reference to your component. You can achieve this in different ways:
Use explicit binding:
methods: {
handleClick () {
this.ctaCaption = this.ctaCaptions[1]
}.bind(this)
}
Or you can use an ES6 arrow function (these preserve the this at the moment of definition rather than at execution time):
methods: {
handleClick: () => {
this.ctaCaption = this.ctaCaptions[1]
}
}
For a more specific and precise insight, you'd have to show the HTML snippet which uses the model code you've shown. Also, no line in your showcased code uses removeChild.

dojox/checkedMultiSelect add option on top AS 'select all'

I am trying to populate the dojox/form/checkedMultiSelect with a top option named: 'select all'.
One way to do this is to use declare function to change the '_addOptionItem' function.
The problem is that this '_addOptionItem' function is using a declared object named: 'formCheckedMultiSelectMenuItem' inside the 'CheckedMultiSelect' widget, AND gives an error with: 'formCheckedMultiSelectMenuItem is not defined'.
How to fix this?
My JS code:
declare_CheckedMultiSelect: function(formCheckedMultiSelectItem){
return declare(CheckedMultiSelect, {
startup: function() {
this.inherited(arguments);
setTimeout(lang.hitch(this, function() {
this.dropDownButton.set("label", this.label);
}));
},
_addOptionItem: function(item){
var item;
if(this.dropDown){
item = new formCheckedMultiSelectMenuItem({
option: option,
parent: this.dropDownMenu
});
c(item)
this.dropDownMenu.addChild(item);
}else{
item = new formCheckedMultiSelectItem({
option: option,
parent: this
});
this.wrapperDiv.appendChild(item.domNode);
}
this.onAfterAddOptionItem(item, option);
}
});
}
Here is working prototype of what you are trying to achieve http://jsfiddle.net/894af/750/ please feel free to ask any follow up question. it is done in different way, but what I simply did is:
1) when create the mutliselect get each check box after creating using
onAfterAddOptionItem
2) listen to the select all checkbox and then override the onclick fucntion and then change the selection of all the checkboxs, based on the selection of the checkbox.
if(option.value == "SA"){
on(item, "click", function(evt){
var optionsToSelect = checkedMultiSelect.getOptions();
for(var i = 0 ; i < optionsToSelect.length;i++){
if(optionsToSelect[i].value == "SA"){
if(optionsToSelect[i].selected){
checkedMultiSelect.set("value",optionsToSelect);
}else{
checkedMultiSelect.set("value",[]);
}
}
}
});
}

Durandal Custom View Location Strategy

I am trying to figure out how to use a custom view location strategy, I have read the documentation at this page http://durandaljs.com/documentation/Using-Composition/ but I don't exactly understand what the strategy function should look like.
Can anybody give me a quick example of what the implementation of this function would be like and the promise that returns (even a simple one) etc?
Thanks in advance,
Gary
p.s. This is the code in my html:
<div>
<div data-bind="compose: {model: 'viewmodels/childRouter/first/simpleModel', strategy:
'viewmodels/childRouter/first/myCustomViewStrategy'}"></div> </div>
and this is the code in my myCustomViewStrategy:
define(function () {
var myCustomViewStrategy = function () {
var deferred = $.Deferred();
deferred.done(function () { console.log('done'); return 'simpleModelView'; });
deferred.fail(function () { console.log('error'); });
setTimeout(function () { deferred.resolve('done'); }, 5000);
return deferred.promise();
};
return myCustomViewStrategy;
});
but I get the error:
Uncaught TypeError: Cannot read property 'display' of undefined - this is after done has been logged in the console window.
Okay I solved this by creating my custom view strategy by the following:
define(['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {
var myCustomViewStrategy = function () {
return viewEngine.createView('views/childRouter/first/sModelView');
}
return myCustomViewStrategy;
});
As I found the documentation a bit lacking on compose binding's strategy setting I checked the source code how it works. To summ it up:
The module specified by the compose binding's strategy setting by its moduleId
must return a function named 'strategy'
which returns a promise which results in the view to be bound
as a HTML element object.
As a parameter the strategy method receives the compose binding's settings object
with the model object already resolved.
A working example:
define(['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) {
var strategy = function(settings){
var viewid = null;
if(settings.model){
// replaces model's module id's last segment ('/viewmodel') with '/view'
viewid = settings.model.__moduleId__.replace(/\/[^\/]*$/, '/view');
}
return viewEngine.createView(viewid);
};
return strategy;
});
Durandal's source:
// composition.js:485
for (var attrName in settings) {
if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) {
/*
* strategy is unwrapped
*/
settings[attrName] = ko.utils.unwrapObservable(settings[attrName]);
} else {
settings[attrName] = settings[attrName];
}
}
// composition.js:523
if (system.isString(context.strategy)) {
/*
* strategy is loaded
*/
system.acquire(context.strategy).then(function (strategy) {
context.strategy = strategy;
composition.executeStrategy(context);
}).fail(function(err){
system.error('Failed to load view strategy (' + context.strategy + '). Details: ' + err.message);
});
} else {
this.executeStrategy(context);
}
// composition.js:501
executeStrategy: function (context) {
/*
* strategy is executed
* expected to be a promise
* which returns the view to be bound and inserted to the DOM
*/
context.strategy(context).then(function (child) {
composition.bindAndShow(child, context);
});
}

Returning value from file read with WinJS for use in page

I currently have an issue with a file read in a Windows 8/WinRT application. I have a simple navigation style app, several pages have access to the same data and I have a data.js file that defines a namespace (Data) with a number of members. One part of the application saves items to a txt file stored in the applications local data folder. But on some of the other pages I need to read this in or check for the existence of an item within the list of previously saved items. To do this I added another method into the data.js file. The trouble is, when I call this method to check for the existence of an item, it doesn't return the value straight away due to the async nature, but the rest of code in the page specific js file still seems to execute before it jumps back into the parsing. This means that the logic to check for an item doesn't seem to work. I have a feeling it's down to my use of either .done or .then but my code is as follows:
DATA.JS
var doesItemExist= function(item_id){
var appFolder = Windows.Storage.ApplicationData.current.localFolder;
//note I've tried this with and without the first "return" statement
return appFolder.getFileAsync(dataFile).then(function (file) {
Windows.Storage.FileIO.readTextAsync(file).done(function (text) {
try {
var json = JSON.parse(text);
if (json) {
for (var i = 0; i < json.items.length; i++) {
var temp_item = json.items[i];
if (temp_item.id === item_id) {
return true;
break;
}
}
} else {
return false;
}
} catch (e) {
return false;
console.log(e);
}
}, function (e) { return false;console.log(e); });
}, function (e) { // error handling
return false;
console.log(e);
});
}
WinJS.Namespace.define("Data", {
doesItemExist: doesItemExist
}); //all of the above is wrapped in a self executing function
Then on Page.js I have the following:
var add = document.getElementById('add');
if (Data.doesItemExist(selected_item.id)) {
add.style.display = 'block';
} else {
add.style.display = 'none';
}
All the variables here are assigned and debugging doesn't produce any errors, control just appears to go back to the if/else statement after it hits the getFileAsync but before it even goes through the for loop. But subsequently it does go in to the for loop but after the if statement has finished. I'm guessing this is down to the async nature of it all, but I'm not sure how to get around it. Any ideas?
thanks
A Promise should work here.
I created a new Navigation app, and added a Data.js file containing the following code:
(function () {
var appData = Windows.Storage.ApplicationData;
function doesItemExist(item_id) {
return new WinJS.Promise(
function (completed, error, progress) {
var exists = false;
appData.current.localFolder.createFileAsync("data.txt", Windows.Storage.CreationCollisionOption.openIfExists).then(
function (file) {
Windows.Storage.FileIO.readTextAsync(file).then(
function (fileContents) {
if (fileContents) {
if (fileContents = "foo!") {
completed(true);
}
else {
completed(false);
}
}
else {
completed(false);
}
}
);
},
function (e) {
error(e);
}
);
}
);
}
WinJS.Namespace.define("Data", {
doesItemExist: doesItemExist
});
})();
Note that I've simplified the code for retrieving and parsing the file, since that's not really relevant to the problem. The important part is that once you've determined whether the item exists, you call completed(exists) which triggers the .then or .done of the Promise you're returning. Note that you'd call error(e) if an exception occurs, as I'm doing if there's an exception from the call to createFileAsync (I use this call rather than getFileAsync when I want to be able to either create a file if it does not exist, or return the existing file if it does, using the openIfExists option).
Then, in Home.js, I added the following code to the ready handler:
var itemExists;
var itemExistsPromise = Data.doesItemExist(42);
itemExistsPromise = itemExistsPromise.then(function (exists) {
itemExists = exists;
var content = document.getElementById("content");
content.innerText = "ItemExists is " + itemExists;
});
itemExistsPromise.done(function () {
var a = 42;
});
var b = 0;
The code above sets the variable itemExistsPromise to the returned promise from the function in Data.js, and then uses an anonymous function in the .then function of the Promise to set the variable itemExists to the Boolean value returned from the doesItemExist Promise, and grabs the <p> tag from Home.html (I added an id so I could get to it from code) and sets its text to indicate whether the item exists or not). Because I'm calling .then rather than .done, the call returns another promise, which is passed into the itemExistsPromise variable.
Next, I call itemExistsPromise.done to do any work that has to wait until after the work performed in the .then above it.
If you set a breakpoint on the lines "var a = 42" and "var b = 0" (only included for the purpose of setting breakpoints) as well as on the line "itemExists = exists", you should find that this gives you the control you need over when the various parts are executed.
Hope that helps!

Can I use Ext's loader to load non-ext scripts/object dynamically?

In my ExtJS 4.0.7 app I have some 3rd party javascripts that I need to dynamically load to render certain panel contents (some fancy charting/visualization widgets).
I run in to the age-old problem that the script doesn't finish loading before I try to use it. I thought ExtJS might have an elegant solution for this (much like the class loader: Ext.Loader).
I've looked at both Ext.Loader and Ext.ComponentLoader, but neither seem to provide what I'm looking for. Do I have to just "roll my own" and setup a timer to wait for a marker variable to exist?
Here's an example of how it's done in ExtJS 4.1.x:
Ext.Loader.loadScript({
url: '...', // URL of script
scope: this, // scope of callbacks
onLoad: function() { // callback fn when script is loaded
// ...
},
onError: function() { // callback fn if load fails
// ...
}
});
I've looked at both Ext.Loader and Ext.ComponentLoader, but neither
seem to provide what I'm looking for
Really looks like it's true. The only thing that can help you here, I think, is Loader's injectScriptElement method (which, however, is private):
var onError = function() {
// run this code on error
};
var onLoad = function() {
// run this code when script is loaded
};
Ext.Loader.injectScriptElement('/path/to/file.js', onLoad, onError);
Seems like this method would do what you want (here is example). But the only problem is that , ... you know, the method is marked as private.
This is exactly what newest Ext.Loader.loadScript from Ext.4-1 can be used for.
See http://docs.sencha.com/ext-js/4-1/#!/api/Ext.Loader-method-loadScript
For all you googlers out there, I ended up rolling my own by borrowing some Ext code:
var injectScriptElement = function(id, url, onLoad, onError, scope) {
var script = document.createElement('script'),
documentHead = typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
cleanupScriptElement = function(script) {
script.id = id;
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
return this;
},
onLoadFn = function() {
cleanupScriptElement(script);
onLoad.call(scope);
},
onErrorFn = function() {
cleanupScriptElement(script);
onError.call(scope);
};
// if the script is already loaded, don't load it again
if (document.getElementById(id) !== null) {
onLoadFn();
return;
}
script.type = 'text/javascript';
script.src = url;
script.onload = onLoadFn;
script.onerror = onErrorFn;
script.onreadystatechange = function() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
onLoadFn();
}
};
documentHead.appendChild(script);
return script;
}
var error = function() {
console.log('error occurred');
}
var init = function() {
console.log('should not get run till the script is fully loaded');
}
injectScriptElement('myScriptElem', 'http://www.example.com/script.js', init, error, this);
From looking at the source it seems to me that you could do it in a bit of a hackish way. Try using Ext.Loader.setPath() to map a bogus namespace to your third party javascript files, and then use Ext.Loader.require() to try to load them. It doesn't look like ExtJS actually checks if required class is defined in the file included.