How to use dojo On with Dojox Searchbox? - dojo

I am following this link http://dojotoolkit.org/reference-guide/1.9/dojox/mobile/SearchBox.html and am trying to do the same in my app. The only difference is that I want to use "onSearch" event using "dojo On" but I am not able to read results, query, options that we get by default in the onSearch function.Please help me in solving this problem.
My HTML code:
<input data-dojo-type="dojox/mobile/SearchBox" type="search" placeHolder="Search"
data-dojo-props='store:store, searchAttr: "label", ignoreCase: true, pageSize:2'>
<ul data-dojo-type="dojox/mobile/RoundRectList" jsId="list"></ul>
My JS code:
define(["dojo/has",
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/_base/array",
"dojo/dom",
"dojo/dom-class",
"dojo/dom-construct",
"dojo/query",
"dojo/dom-style",
"dojo/dom-attr",
"dojo/on",
"dojo/_base/Deferred",
"dojo/topic",
"dojo/_base/connect",
"dijit/registry",
"dojo/store/Memory",
"dojox/mobile/SearchBox",
"dojo/selector/acme"
],
function(has,declare,lang,array,dom,domClass,domConstruct,query,domStyle,domAttr,on,Deferred,topic,connect,registry,MemoryStore,SearchBox)
{
declare("controllers.SearchController", [], {
started:false,
constructor : function(args) {
WL.Logger.debug("SearchController created");
lang.mixin(this,args);
},
start:function(){
if(!this.started)
{
console.log("i am in SearchController.start");
this.subscription();
this.started = true;
}
},
subscription:function(){
store = new MemoryStore({data: [
{label: "Alabama"},
{label: "Alaska"},
{label: "American Samoa"},
{label: "Arizona"},
{label: "Arkansas"},
{label: "Kansas"},
{label: "Kentucky"}
]});
var searchbox=registry.byId("searchbox");
on(searchbox.domNode,"search",lang.hitch(this,this.onSearch));
},
onSearch: function (results, query, options) {
// this.onSearch = function () {};
console.log(results);
}
});
return controllers.SearchController;
}
);
Also, I am following this link dojox/mobile/SearchBox 'onSearch' event runs twice on webkit
to use the workaround for dojox searchbox. How can I implement it in my case?

You should never try to access widget events through DOM nodes. There is a difference between widgets and DOM nodes, and this is one of them. Also, because dojo/on can only be used with DOM nodes and DOM events, you cannot use it to handle the onSearch event.
Every widget has a on() function that you can use to attach widget event handlers. For example:
searchbox.on("search", lang.hitch(this, this.onSearch));
If the event runs twice, you can try doing something like this (you will probably have to rewrite this in your object oriented design):
var myEventHandler = searchbox.on("search", lang.hitch(this, this.onSearch());
myEventHandler.remove();
According to the API documentation the return value of the on() function is undefined, but this topic its stated that it returns an object containing a remove() function able to remove the event listener.
I don't think it's possible. If you want to retrieve data from your database/webservice, you could use the dojo/store/JsonRest store (RESTful webservices) or you could implement your own store (or fetch the data and put it in a dojo/store/Memory).
Dojo chooses for an abstraction layer upon your data implementation called the store API. The advantages of these are that, because it's an abstraction layer, that you can use your store for multiple purposes (all Dijit widgets, Dojo mobile widgets, ...) work in a similar way that they use a store.

Concerning this part of your question:
I am following this link dojox/mobile/SearchBox 'onSearch' event runs twice on webkit to use the workaround for dojox searchbox. How can I implement it in my case?
I do not think such a workaround is needed. As I wrote in this answer, as long as you have a store specified, SearchBox.onSearch() should be called only once.
In short: just do not apply this workaround, it shouldn't be necessary.

In addition to the event mistake pointed out by Dmitri, there's an issue with the order of execution.
When does Dojo parse your HTML? Do you have parseOnLoad:true in your dojoConfig (or data-dojo-config)?
When the parser reaches data-dojo-type="dojox/mobile/SearchBox", it will try to instantiate a SearchBox widget. Because you have specified store:store in its properties, it will look for a variable called store.
Now, the store variable itself gets instantiated in your SearchController. So you have to make sure that subscription() is called before the parser runs. However, the subscription() method in turn tries to look for a widget called "searchbox". So the parser has to be called before subscription(). As you can tell, this isn't going to work :)
So you have to rewrite the SearchController a bit. For example, you can remove the store:store from data-dojo-props, and let the controller set it in the subscription method:
var store = new MemoryStore({data: [....]});
var searchbox = registry.byId("searchbox");
searchbox.set("store", store);
searchbox.on("search", lang.hitch(this, this.onSearch)); // See Dmitri's answer.

Related

How can I hide a dijit/form/button?

I think it is a common sense that providing a simple way to hide/show and enable/disable a button, but I cannot find any document that describe dojo has done such thing.
Any way, I hope it is my fault that I have missed out something while googling, thanks!
The following coding is what I have tried but they just make the button's text invisible:
dojo.style(btnInsert, {'visibility':'hidden'});
dojo.style(btnInsert, {'display':'none'});
UPDATE Question:
To oborden2:
I have tried your code, the result is same as the above code, here is the captured screen:
To MiBrock:
I have also tried your code and also get the result that same as the above code:
Form widgets in Dijit are special. For all normal Dijit widgets, the domNode (outermost node) of the widget receives the id property. However, with form widgets, the focusNode (which corresponds to the <input> element) receives the ID instead, so that things like <label for="foo"> work properly. In this case, the outermost node has no ID, and you’re actually just hiding the inner HTML input element.
If you already have reference to the widget:
require([ 'dojo/dom-style' ], function (domStyle) {
domStyle.set(widget.domNode, 'display', 'none');
});
If you only have a reference to the ID of the widget/original DOM node:
require([ 'dojo/dom-style', 'dijit/registry' ], function (domStyle, registry) {
domStyle.set(registry.byId(nodeId).domNode, 'display', 'none');
});
Try
require(["dojo/dom-style","dojo/domReady!"], function(domStyle){
domStyle.set(dojo.byId(domNode),'display','none');
});
The variable "domNode" stays for the id of the Node that should be influenced. This is the way we make it.
Regards, Miriam
Try using the Toggler module
require(["dojo/fx/Toggler"], function(Toggler),{
// Create a new Toggler with default options
var toggler = new Toggler({
node: "btnInsert"
});
// Hide the node
toggler.hide();
// Show the node
toggler.show();
});
http://dojotoolkit.org/reference-guide/1.9/dojo/fx/Toggler.html
I imagine you would want to link this to some event using Dojo's on module. Link it up to whatever condition triggers the button's need to be hidden.

Dojo1.8: _WidgetBase does not sound good to me

Hi It seems that using _WidgetBase is is a bad idea to use.
What I was looking for is that I can make instances (with different properties from the class button).
require(["dojo/_base/declare", "dojo/dom","dojo/dom_construct", "dijit/_WidgetBase", dojo/domReady!],
function(declare, dom, domConstruct, _WidgetBase)
{
ready(function()
{
declare("myBtn", [_WidgetBase],
{buildRendering: function()
{
this.domNode = domConstruct.create('button');
}
});
registry.byId(new myBtn(
{id:'btn1',
label:'HelloA'
}).placeAt(dom.byId('line1')));
registry.byId(new myBtn(
{id:'btn2',
label:'HelloB'
}).placeAt(dom.byId('line2')));
registry.byId(new myBtn(
{id:'btn3',
label:'HelloC'
}).placeAt(dom.byId('line3')));
}
});
So I am wondering if it is okay to use _WidgetBase, when I wanted to add different properties for each button?
I am not sure if I understand your issue, while you can just use dijit/form/button (http://dojotoolkit.org/api/1.8/dijit/form/Button). If the button is just an example and you still need to extend _WidgetBase - answer to your question is yes, it is ok to use it, but there's a bit more code to write to make it configurable and flexible.

Dojo declarative vs. programmatic creation of Select elements with stores

I'm trying to hook up a Select element with a Dojo store. The Select element is declared in HTML and I'm trying to give it a store in some JavaScript code.
It seems the Dojo documentation recommends against this and is in favor of programatically creating the Select element when using a store. However this is a yellow flag to me because I like to keep creation of HTML elements separate from their behavior. In this case, it would be ideal if I could keep the Select element in HTML and hook up the store in JavaScript.
Is the statement in the Dojo docs really the 'best practice' for this? I'm looking for opinions from experienced Dojo developers as I'm still getting my feet wet with Dojo.
Intuitively one would use select.set("store", store) to assign/change store to a dijit as all widgets are dojo/Stateful, but surprisingly it does not work.
Anyway there is a method select.setStore(store, selectedValue, fetchArgs) which (also surprisingly) is not deprecated and works.
Define dijit/form/Select without a store:
<select id="select1" data-dojo-type="dijit/form/Select"></select>​
Assign a store to it:
require([
"dojo/ready",
"dijit/registry",
"dojo/store/Memory",
], function(
ready, registry, Memory
) {
ready(function() {
var store1 = new Memory({
idProperty: "value",
data: [
{ value: "AL", label: "Alabama" },
{ value: "AK", label: "Alaska" },
{ value: "AZ", label: "Arizona" }
]
});
var select1 = registry.byId("select1");
select1.set("labelAttr", "label");
select1.setStore(store1, "AZ");
});
});
See it in action at jsFiddle: http://jsfiddle.net/phusick/ZmsYV/
Adding some UX sugar to the aforementioned I would create dijit/form/Select disabled with single option e.g. Loading... and its final desired width:
<select
id="select1"
data-dojo-type="dijit/form/Select"
data-dojo-props="disabled:true"
style="width:150px;"
>
<option>Loading...</option>
</select>​
Then I would enable it after calling setStore():
var select1 = registry.byId("select1");
select1.set("labelAttr", "label");
select1.setStore(store1);
select1.set("disabled", false);
See this enhanced version at work: http://jsfiddle.net/phusick/xdDEm/
Debugging bad store data/definitions can get pretty nasty when doing so declaratively. Additionally, you may run into strange annoyance when trying to create multiple of the same widget following a declaratively built select/store combination. For example (pseudocode):
<div dojotype="dojox.data.QueryReadStore" url="someurl/blah.do" jsId="mystore"/>
<select dojotype="dijit.form.FilteringSelect" store="mystore">
</select>
The would in theory do what you want by binding mystore to the select, however if you were to create multiple of this widget, you'd have an id conflict with "mystore." As a workaround you'd have to do something like jsId="${id}_mystore" for both the jsId and the store's id.
One option if you would like to keep a declarative behavior is to have attachpoints for both your store and your select, then you can simply call selectwidget.set("store",mystore) after initialization.

.queue() and .proxy(), animation timing in jQuery

I'm working on a pseudo plugin (just really an namespaced initializer on the jQuery object) and I'm having a bit of trouble with .proxy() and .queue() (seemingly two of the most misunderstood methods around)
Anyways, I thought I had the logic sorted out; the function $.cb() takes a map of functions as such:
$.cb({
'show': function(){ },
'hide': function(){ },
'open': function(){ },
'close': function(){ },
'beforeUpdate': function(){ },
'afterUpdate': function(){ }
});
These functions (should) contain animation sequences applied to $(this), the context of which has internally, via .proxy(), been changed to the respective element(s). They are stored in a settings variable, available to all methods of the "plugin".
Internally, some namespaced event handlers, attached via .live({ }):
// ...
'cb.hide': function(event){
if(event.isPropagationStopped()){
return false;
}
event.stopPropagation();
$.proxy(settings.hide, this)();
$(this).hide();
},
'cb.update': function(event, html){
if(event.isPropagationStopped()){
return false;
}
event.stopPropagation();
$.proxy(settings.beforeUpdate, this)();
$(this).html(html);
$.proxy(settings.afterUpdate, this)();
},
// ...
Anyways, the purpose is that there in inherent functionality brought to the table using this "plugin", but the implementer can pass the function map to opt for different transitional animations.
The problem, is that I can't seem to get these functions to queue properly; different ones taking precedence, etc. I've tried mocking around with .queue() but I can't seem to get anything right with it:
// in cb.update
var $this = $(this);
$(this).queue(function(next){
$.proxy(settings.beforeUpdate, $this)();
next();
}).queue(function(next){
$this.html(html);
next();
}).queue(function(next){
$.proxy(settings.afterUpdate, $this)();
}).dequeue();
The problem is especially prevalent with the 'cb.update' event, as the order should be:
beforeUpdate is called (animation sequence occurs and completes)
The element's contents are updated via .html()
afterUpdate is called (animation sequence occurs and completes)
Whats actually happening is:
The element's contents are updated via .html()
beforeUpdate is called (animation sequence occurs and completes)
afterUpdate is called (animation sequence occurs and completes)
So given the supplied animation is simply .fadeOut() and fadeIn() for beforeUpdate and afterUpdate respectively, it's updating the contents, then fading out and in.
So, any suggestions on this sort of implementation? How can I ensure the proper ordering of the events/animations? Have I gone a wildly stupid route in terms of trying to implement such a feature?

Using dijit.InlineEditBox with dijit.form.Select

I'm trying to use a dijit.form.Select as the editor for my dijit.InlineEditBox. Two problems / unexpected behavior seem to occur:
Inconsistently, the InLineEditBox doesn't have the initial value set as selected
Consistently, after selecting a choice, the value that should be hidden is shown instead of the label.
The width isn't set to 130px
Here's working code: http://jsfiddle.net/mimercha/Vuet8/7/
The jist
<span dojoType="dijit.InlineEditBox" editor="dijit.form.Select"
editorParams="{
options: [
{label:'None',value:'none'},
{label:'Student',value:'stu'},
{label:'Professor',value:'prof',selected:true},
],
style:'width:1000px;',
}"
editorStyle="width: 1000px;"
>
</span>
Any help is greatly appreciated! Thanks!
Okay, after a few MORE hours struggling with the mess that is dijit.InlineEditBox, I think I have the solution to the remaining issue (#2).
EDIT: My first solution to #2 is still flawed; the implementation at http://jsfiddle.net/kfranqueiro/Vuet8/10/ will never return the actual internal value when get('value') is called.
EDIT #2: I've revamped the solution so that value still retains the real (hidden) value, keeping displayedValue separate. See if this works better:
http://jsfiddle.net/kfranqueiro/Vuet8/13/
First, to recap for those who weren't on IRC:
Issue #1 was happening due to value not being properly set as a top-level property of the InlineEditBox itself; it didn't pick it up properly from the wrapped widget.
Issue #3 was happening due to some pretty crazy logic that InlineEditBox executes to try to resolve styles. Turns out though that InlineEditBox makes setting width particularly easy by also exposing it as a top-level numeric attribute. (Though IINM you can also specify a percentage as a string e.g. "50%")
Now, issue #2...that was the killer. The problem is, while InlineEditBox seems to have some logic to account for widgets that have a displayedValue attribute, that logic is sometimes wrong (it expects a displayedValue property to actually exist on the widget, which isn't necessarily the case), and other times missing entirely (when the InlineEditBox initializes). I've worked around those as best I could in my own dojo.declared extensions to InlineEditBox and the internal widget it uses, _InlineEditor - since generally it's a good idea to leave the original distribution untouched.
It's not pretty (neither is the underlying code I dug through to understand and come up with this), but it seems to be doing its job.
But man, this was rather interesting. And potentially pertinent to my interests as well, as we have used this widget in our UIs as well, and will be using it more in the future.
Let me know if anything backfires.
hm...
<span dojoType="dijit.InlineEditBox" editor="dijit.form.Select"
editorParams="{
options: [
{label:'None',value:'none'},
{label:'Student',value:'stu'},
{label:'Professor',value:'prof',selected:true},**<<<<** and this comma is for?
],
style:'width:1000px;',**<<<<** and this comma is for?
}"
editorStyle="width: 1000px;"
>
</span>
Also, when using dijit.form.Select, selected value is not attr "selected" but value.
And if you enter prof inside <span ...blah > prof </span> than your proper selected option will be selected ;)
Dijit select checks for VALUE, not attr.
This may be fixed in recent Dojo - see http://bugs.dojotoolkit.org/ticket/15141 - but using 1.7.3 I found this worked:
In my app directory, at the same level as dojo, dijit and dojox, I created a file InlineSelectBox.js which extends InlineEditBox with code to set the HTML on the associated domNode from the value of the Dijit, and which wires up that code to the onChange() event:
define(["dijit/InlineEditBox",
"dijit/form/Select",
"dojo/on",
"dojo/_base/declare",
"dojo/_base/array"
],
function(InlineEditBox, Select, on, declare, array){
return declare(InlineEditBox, {
_setLabel: function() {
array.some(this.editorParams.options, function(option, i){
if (option.value == this.value) {
this.domNode.innerHTML = option.label;
return true;
}
return false;
}, this);
},
postMixInProperties: function(){
this.inherited(arguments);
this.connect(this, "onChange", "_setLabel");
},
postCreate: function(){
this.inherited(arguments);
this._setLabel();
}
});
});
Then, in my view script:
require(["dojo/ready",
"app/InlineSelectBox",
"dijit/form/Select"
],
function(ready, InlineSelectBox, Select){
ready(function(){
// Add code to set the options array
var options = [];
// Add code to set the initial value
var initialValue = '';
var inlineSelect = new InlineSelectBox({
editor: Select,
editorParams: {options: options},
autoSave: true,
value: initialValue
}, "domNodeToAttachTo");
});
});
I was dealing with this situation a few months ago, and not finding a resolution i made my own algorithm.
I put a div with an event on Onclick that build programatically a Filtering Select on that div with the store i want to use.
function create(id,value){
var name = dojo.byId(id).innerHTML;
dojo.byId(id).parentNode.innerHTML = '<div id="select"></div>';
new dijit.form.FilteringSelect({
store: store,
autoComplete: true,
invalidMessage:"Invalid Selection",
style: "width: 80px;",
onBlur: function(){ },
onChange: function(){ },
required: true,
value: value,
disabled: false,
searchAttr: "name",
id: "status"+id,
name: "status"
},"select");
dijit.byId('status'+id).focus();
}
I used the onBlur event to destroy the widget and the onchange to save by xhr the new value.
The focus is below because the onBlur was not working properly.
note: the function is not complete.