Autodesk Forge Viewer3d search using attributeNames - autodesk-forge

I'm trying to implement .search() and restrict attributeNames using the optional parameter but it always brings back an empty array.
https://developer.autodesk.com/en/docs/viewer/v2/reference/javascript/viewer3d/
Can someone clarify how this filter is being applied? I was expecting it to look at the returned property.displayName but apparently that's not the case.
Example:
viewer.search('13-097', function (ids) {
console.log(ids);
var id = ids[0];
viewer.getProperties(id, function (obj) {
console.log(obj.properties);
});
}, function (e) { });
viewer.search('13-097', function (ids) {
console.log(ids);
}, function (e) { }, ['ADDRESS']);
Output:
first search:
[8095]
second search:
[]
from object 8095, properties:
10:Object
displayCategory:"DWF - Construction"
displayName:"ADDRESS"
displayValue:"13-097"
hidden:false
type:20
units:null

Please note the Autodesk.Viewing.Viewer3D.search() method is NOT case sensitive on the text parameter, but it IS case sensitive on the attributeNames parameter, and you need to use the full name of the attribute.
If you are using the displayName of properties to correlate, note that viewer.getProperties() is currently returning the displayName. When there is no displayName, then (and only then) attribute name is returned.
Below is a sample I tried before (adjusted to your dataset):
function search() {
viewer.clearSelection(); // remove previously highlighted searches
var searchStr = '13-097';
var searchPropList = new Array('ADDRESS');
viewer.search(searchStr, searchCallback, searchErrorCallback, searchPropList);
}
function searchCallback(ids) {
alert(ids.length);
}
function searchErrorCallback(error) {
console.log(error);
}
EDIT (Oct 24, 2016)
The Viewer 2.11 .getProperties method returns attributes, which can be used on the .search attributesNames parameter.

Related

How works this in arrow functions [duplicate]

I've read in several places that the key difference is that this is lexically bound in arrow functions. That's all well and good, but I don't actually know what that means.
I know it means it's unique within the confines of the braces defining the function's body, but I couldn't actually tell you the output of the following code, because I have no idea what this is referring to, unless it's referring to the fat arrow function itself....which doesn't seem useful.
var testFunction = () => {
console.log(this)
};
testFunction();
Arrow functions capture the this value of the enclosing context
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
So, to directly answer your question, this inside your arrow function would have the same value as it did right before the arrow function was assigned.
In order to provide the big picture I'm going to explain both, dynamic and lexical binding.
Dynamic Name Binding
this refers to the object the method is called on. This is a regularly to be read sentence on SO. But it is still only a phrase, pretty abstract. Is there a corresponding code pattern to this sentence?
Yes there is:
const o = {
m() { console.log(this) }
}
// the important patterns: applying methods
o.m(); // logs o
o["m"](); // logs o
m is a method because it relies on this. o.m() or o["m"]() means m is applied to o. These patterns are the Javascript translation to our famous phrase.
There is another important code pattern that you should pay attention to:
"use strict";
const o = {
m() { console.log(this) }
}
// m is passed to f as a callback
function f(m) { m() }
// another important pattern: passing methods
f(o.m); // logs undefined
f(o["m"]); // logs undefined
It is very similar to the previous pattern, only the parenthesis are missing. But the consequences are considerable: When you pass m to the function f, you pull outm of its object/context o. It is uprooted now and this refers to nothing (strict mode assumed).
Lexical (or Static) Name Binding
Arrow functions don't have their own this/super/arguments binding. They inherit them from their parent lexical scope:
const toString = Object.prototype.toString;
const o = {
foo: () => console.log("window", toString.call(this)),
bar() {
const baz = () => console.log("o", toString.call(this));
baz();
}
}
o.foo() // logs window [object Window]
o.bar() // logs o [object Object]
Apart from the global scope (Window in browsers) only functions are able to form a scope in Javascript (and {} blocks in ES2015). When the o.foo arrow function is called there is no surrounding function from which baz could inherit its this. Consequently it captures the this binding of the global scope which is bound to the Window object.
When baz is invoked by o.bar, the arrow function is surrounded by o.bar (o.bar forms its parent lexical scope) and can inherit o.bar's this binding. o.bar was called on o and thus its this is bound to o.
Hope this code show could give you clearer idea. Basically, 'this' in arrow function is the current context version of 'this'. See the code:
// 'this' in normal function & arrow function
var this1 = {
number: 123,
logFunction: function () { console.log(this); },
logArrow: () => console.log(this)
};
this1.logFunction(); // Object { number: 123}
this1.logArrow(); // Window
Arrow function this is pointing to the surrounding parent in Es6, means it doesn't scope like anonymous functions in ES5...
It's very useful way to avoid assigning var self to this which is widely used in ES5...
Look at the example below, assigning a function inside an object:
var checkThis = {
normalFunction: function () { console.log(this); },
arrowFunction: () => console.log(this)
};
checkThis.normalFunction(); //Object {}
checkThis.arrowFunction(); //Window {external: Object, chrome: Object, document: document, tmpDebug: "", j: 0…}
You can try to understand it by following the way below
// whatever here it is, function or fat arrow or literally object declare
// in short, a pair of curly braces should be appeared here, eg:
function f() {
// the 'this' here is the 'this' in fat arrow function below, they are
// bind together right here
// if 'this' is meaningful here, eg. this === awesomeObject is true
console.log(this) // [object awesomeObject]
let a = (...param) => {
// 'this is meaningful here too.
console.log(this) // [object awesomeObject]
}
so 'this' in fat arrow function is not bound, means you can not make anything bind to 'this' here, .apply won't, .call won't, .bind won't. 'this' in fat arrow function is bound when you write down the code text in your text editor. 'this' in fat arrow function is literally meaningful here. What your code write here in text editor is what your app run there in repl. What 'this' bound in fat arror will never change unless you change it in text editor.
Sorry for my pool English...
Arrow function never binds with this keyword
var env = "globalOutside";
var checkThis = {env: "insideNewObject", arrowFunc: () => {
console.log("environment: ", this.env);
} }
checkThis.arrowFunc() // expected answer is environment: globalOutside
// Now General function
var env = "globalOutside";
var checkThis = {env: "insideNewObject", generalFunc: function() {
console.log("environment: ", this.env);
} }
checkThis.generalFunc() // expected answer is enviroment: insideNewObject
// Hence proving that arrow function never binds with 'this'
this will always refer to the global object when used inside an arrow function. Use the regular function declaration to refer to the local object. Also, you can use the object name as the context (object.method, not this.method) for it to refer to the local object instead of the global(window).
In another example, if you click the age button below
<script>
var person = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: function() {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
var person2 = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: () => {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
</script>
<input type=button onClick="alert(person2.age());" value="Age">
it will throw an exception like this
×JavaScript error: Uncaught TypeError: Cannot read property
'getFullYear' of undefined on line 18
But if you change person2's this line
return new Date().getFullYear() - this.dob.getFullYear();
to
return new Date().getFullYear() - person2.dob.getFullYear();
it will work because this scope has changed in person2
Differences between arrow functions to regular functions: (taken from w3schools)
With arrow functions there are no binding of this.
In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.
With arrow functions the this keyword always represents the object that defined the arrow function.
// Regular Function:
hello = function() {
document.getElementById("demo").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
// -------------------------------------------
// Arrow function
hello2 = () => {
document.getElementById("demo2").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello2);
// A button object calls the function:
document.getElementById("btn2").addEventListener("click", hello2);
<p><i>With a regular function this represents the <b>object that calls the function</b>:</i></p>
<button id='btn'>click me regular function</button>
<p id="demo">Regular function: </p>
<hr>
<p><i>With arrow function this represents the <b>owner of the function(=the window object)</b>:</i></p>
<button id='btn2'>click me arrow function</button>
<p id="demo2">Arrow function: </p>
A related issue:
Came from - Why can't I access `this` within an arrow function?
We know below from here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Does not have its own bindings to this or super, and should not be used as methods.
Arrow functions establish "this" based on the scope the Arrow function is defined within.
Had a issue with this using arrow functions, so created a class (can be function), and class variable is accessed in arrow function, thereby achieved smaller functions using arrow functions without function keyword:
class MyClassOrFunction {
values = [];
size = () => this.values.length;
isEmpty = () => this.size() === 0;
}
let obj = new MyClassOrFunction();
obj.size(); // function call here
You can also have a getter like this, that does not have function keyword, but a bit longer due to return statement, also can access other member functions:
class MyClassOrFunction {
values = [];
size = () => this.values.length;
get length() { return this.size(); }
}
let obj = new MyClassOrFunction();
obj.length; // NOTE: no function call here

backbone render collection return one object

i have problem rendering my view...the view return always the last in the json object: This is the code:
Router.js:
var list = new clientCollection();
var cards = new cardsView({model:list})
list.fetch({success: function (collection, response, options) {
cards.render();
}
});
Cards.js view:
....
tagName: 'section',
className: 'list',
template: Handlebars.compile(cardsTemplate),
render: function () {
var list = this.model.toJSON(),
self = this,
wrapperHtml = $("#board"),
fragment = document.createDocumentFragment();
$(list).each(function (index, item) {
$(self.el).html(self.template({card: item}));
$.each(item.cards, function (i, c) {
var card = new cardView({model : c});
$(self.el).find('.list-cards').append(card.render().el);
});
fragment.appendChild(self.el);
});
wrapperHtml.append(fragment.cloneNode(true));
},
...
This is my json data:
[
{"id":"9","name_client":"XXXXXXX","cards":[]},
{"id":"8","name_client":"XXXXXXX","cards":[{"id":"8","title":"xxxxx.it","description":"some desc","due_date":"2016-01-23","sort":"0"}]}
]
Can u help me to render the view?
It's hard to know for sure without seeing how the view(s) are attached to the DOM, but your problem appears to be this line ...
$(self.el).html(self.template({card: item}));
That is essentially rendering each element in the collection as the full contents of this view, then replacing it on each iteration. Try instead appending the contents of each template to the view's element.
Also, since you tagged this with backbone.js and collections, note that the easier, more Backbone-y way to iterate through a collection would be:
this.model.each(function(item) {
// 'item' is now an instance of the Backbone.Model type
// contained within the collection. Also, note the use
// of 'this' within the iterator function, as well as
// this.$el within a View is automatically the same as
// $(self.el)
this.$el.append(this.template({ card: item });
// ... and so on ...
// By providing 'this' as the second argument to 'each(...)',
// the context of the iterator function is set for you.
}, this);
There's a lot packed in there, so ...
Backbone.Collection Underscore Methods
Backbone.View this.$el

AngularJS $http and filters

I have a JSON file, which contains:
{
"/default.aspx": "headerBg",
"/about.aspx": "aboutBg",
"/contact.aspx": "contactBg",
"/registration.aspx": "regBg",
"/clients.aspx": "clientsBg",
"/onlinesessions.aspx": "bg-white-box",
"/ondemamdsessions.aspx": "bg-grey"
}
Now I am reading this json file using $http, but I want to add a filter in below fashion:
Using window.location.pathname, I am reading path of the current page, suppose the current page is /about.aspx
Then I want to add a filter in $http response by which I want to read only aboutBg.
The code I wrote can retrieve all the values, but unable to filter that. Please help.
User this function where you receive the response.
function getPageBgClass(currentPage, responseData) {
if (responseData.hasOwnProperty(currentPage))
return responseData[currentPage]
else
return "none"
}
Here is how it should be used in your promise then function
function(response) {
var bg = getPageBgClass(window.location.pathname, response.data);
//Your code here ...
}
there is no direct method to get key using value from json.
you should make sure that there are no 2 keys having same value for below code to work
function swapJsonKeyValues(input) {
var one, output = {};
for (one in input) {
if (input.hasOwnProperty(one)) {
output[input[one]] = one;
}
}
return output;
}
var originaJSON = {
"/default.aspx": "headerBg",
"/about.aspx": "aboutBg",
"/contact.aspx": "contactBg",
"/registration.aspx": "regBg",
"/clients.aspx": "clientsBg",
"/onlinesessions.aspx": "bg-white-box",
"/ondemamdsessions.aspx": "bg-grey"
}
var invertedJSON = swapJsonKeyValues(originaJSON);
var samplepathname = "aboutBg";
var page = invertedJSON[samplepathname];
[function swapJsonKeyValues from https://stackoverflow.com/a/1970193/1006780 ]

Select2 and JSON Data

I am using select2 version 4 and I have a REST service control on an XPage, that reads the fullname column from the names.nsf.
I have the search working, but for some reason, I don't get a list of values back I can select.
The JSON object being returned, looks something like this:
[{"#entryid":"1376-E6D5EBE8ADBEFA7088257DF8006E4BA2","fullname":"Full Name\/OU\/O"},{"#entryid":"1375-FD1CB92A13BFD0E088257DE4006756D7","fullname":"Another Full Name\/OU\/O"}]
The code to initialize the select2 looks like this:
x$( "#{id:comboBox1}" ).select2({
ajax: {
url: "xJSON.xsp/names",
dataType: 'json',
delay: 250,
data: function (params) {
return {
search:'[fullname=]*'+params.term+'*',
// q: params.term, // search term
page: params.page
};
},
results: function (data, page){
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
console.log(data);
return {
results: data
};
},
cache: true
},
//escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1
});
When I look at the browser's console, I can see that the search worked and JSON objects are being returned, however, I don't get a list of values to select from.
For the result return I've tried results: data.fullname and results: data, text:'fullname' but nothing happens.
What am I doing worng?
You need to either switch your JSON response to include id and text for each object, or re-map them in your processResults method. These two properties are required on all selectable objects now in Select2 4.0. Since I'm assuming you either can't change your JSON response, or it wouldn't make sense to, you can easily re-map the data with the following processResults method.
processResults: function (data) {
var data = $.map(data, function (obj) {
obj.id = obj.id || obj["#entityid"];
obj.text = obj.text || obj.fullname;
return obj;
});
return {
results: data
};
});
This will map the #entityid property to the id property and the fullname property to the text property. So selections will be sent to your server containing the #entityid and will be displayed using the fullname.
Also, the results method is no longer needed in Select2 4.0. This was renamed to the current processResults method.
I copied your code exactly as it is, and just changed the fieldname and the search query and worked out just fine.
This is my JSON looks like
[{"#entryid":"1482-AD112B834158AD0D80257E4B004EC42E","#unid":"AD112B834158AD0D80257E4B004EC42E","id":"Victor Hunter","text":"Odhran Patton"},{"#entryid":"1496-291F2480D806A91E80257E4B004EC3D2","#unid":"291F2480D806A91E80257E4B004EC3D2","id":"Wesley O'Meara","text":"Wesley O'Meara"},{"#entryid":"1421-CC19D06880F5DC2980257E4B004EC537","#unid":"CC19D06880F5DC2980257E4B004EC537","id":"Stephen Woods","text":"Emma Doherty"}]
What I know is that select2 expects an id, and a text parameters from the JSON.

HTML5 pushState using History.js. Trouble retrieving data from State.data

I can set data into the State.data of History.js, like this:
var pushStateData = {};
function RetrieveSearchResults(type, url, searchData) {//, showResetButton,
controlToFocus, navDirection) {
pushStateData = {
SearchType : type,
SearchData : searchData,
};
RetrievePageResults(true, url, pushStateData);
}
function RetrievePageResults(pushNewUrl, url, pushStateData) {
navigationInProgress = true;
if (pushNewUrl) {
if (window.History) {
window.History.pushState(pushStateData, null, url);
}
$.get(url, pushStateData.SearchData, function (reply) {
$("#search-results").html(reply);
navigationInProgress = false;
});
}
If I set a breakpoint on the window.History.pushState statement, in Chrome, I can clearly see pushStateData has the desired values.
However, when I try to retrieve the data:
$(window).bind("statechange", function (e) {
if (!navigationInProgress) {
var State = window.History.getState();
if (window.console && window.console.log) {
console.log("popstate", State, window.location.href);
}
RetrievePageResults(false, State.cleanUrl, State.data);
}
});
When I set a breakpoint on the RetrievePageResults statement,
The State.data object no longer has any of the values I set. State.data is defined, and is not null, but it is an empty object without any apparent values.
Thanks,
Scott
I don't see anything wrong with State.data, when you issue a pushState, make sure you call the History.js method:
History.pushState({state:1}, "State 1", "?state=1");
Where:
First Parameter => The data
Second Parameter => The name
Third Parameter => The url
It seems your not passing the state, and the data will only be present if and only if you call the History.pushState. When your visiting the URL directly (/?state=1) you would have no data in the state, data will only be available when navigating back/forward while pushing state via History.pushState.
side note: Make sure your navigationInProgress variable is fixed, you don't want it to be stalled there. Reset it when the $.get request failed when listening on the error callback. And when your pushNewUrl is false, reset the navigationInProgress attribute.