Accessing a local variable/method within a nested require blocks? - dojo

I am not finding in the documentation how to access a local variable of method of the class from within a nested require blocks.
declare( "Clust", StrictIntHashMap,
{
constructor : function()
{
},
cust : function( custId )
{
return this.get( custId );
},
add : function( custObject )
{
this.set( custObject.custId, custObject );
},
reloadThecustses : function()
{
that = this;
require( [ 'inst/DataExtractor', 'inst/ClustTree' ], function ( de, theTree )
{
de.getPlainJSON( Commandz.COMMAND_GET_CUSTS,
function ( dataR )
{
that.add( new Customer( dataR.root[c] ) ); // not working
this.cust( 0 ); // not working
theTree.refreshTheData( dataR.root );
} );
} );
}
} );
return Clust;
How to access the method "add" of the class from within the require block ?
How to access the local variable "that" from within the require block ?

You should be able to access variables defined in the parent scope when using require, since it's equivalent to just having a child scope.
I'm not entirely sure what you are trying to access, but I assume it's the Clust instance.
Would this code work for you?
declare( "Clust", StrictIntHashMap, {
constructor : function() {
},
cust : function( custId ) {
return this.get( custId );
},
add : function( custObject ) {
this.set( custObject.custId, custObject );
},
reloadThecustses : function() {
var clustInstance = this;
require( [ 'inst/DataExtractor', 'inst/ClustTree' ],
function ( de, theTree ) {
de.getPlainJSON( Commandz.COMMAND_GET_CUSTS, function ( dataR ) {
clustInstance.add( new Customer( dataR.root[c] ) );
clustInstance.cust( 0 );
theTree.refreshTheData( dataR.root );
});
});
}
});
return Clust;

Perhaps the problem is caused by having the wrong context in the callback function to getPlainJSON. dojo.hitch() will fix this:
reloadThecustses : function()
{
require( [ 'inst/DataExtractor', 'inst/ClustTree', 'dojo/_base/lang' ], function ( de, theTree, lang )
{
de.getPlainJSON( Commandz.COMMAND_GET_CUSTS,
lang.hitch( function ( dataR )
{
this.add( new Customer( dataR.root[c] ) ); // not working
this.cust( 0 ); // not working
theTree.refreshTheData( dataR.root );
}, this )
} );
}

Related

Load CSS from a dynamically imported ES6 module

My project is being built with Webpack via Laravel Mix. I want to dynamically import an ES6 module that itself imports other modules and a stylesheet. Here is the dynamically imported module (loadJQueryTextillate.js):
import style from 'animate.css/animate.css';
import 'letteringjs';
import 'textillate';
style.use();
export default () => {
};
Here is the module that dynamically imports loadJQueryTextillate.js (animatedText.js):
import isInViewport from './isInViewport';
function maybeAnimateText( elem ) {
const $el = $( elem );
let bounding,
el_html,
el_lines,
in_viewport = $el.data( 'in-viewport' ) || false;
const viewport_height = window.innerHeight || document.documentElement.clientHeight;
if ( $el.hasClass( 'opaque' ) ) {
bounding = elem.getBoundingClientRect();
if ( in_viewport && !isInViewport( elem ) && ( bounding.top > viewport_height ) ) { // Element scrolled off screen
in_viewport = false;
$el.removeClass( 'opaque' ).find( 'ul.texts' ).remove().end().text( $.trim( $el.text() ) );
} else if ( isInViewport( elem ) ) {
in_viewport = true;
}
$el.data( 'in-viewport', in_viewport );
return;
} else if ( !isInViewport( elem ) ) {
return;
}
el_html = $el.html();
el_lines = el_html.split( /<br\s*\/?>/ );
$.each( el_lines, function( key, line ) {
el_lines[ key ] = $.trim( line );
} );
el_html = '<span class="line">' + el_lines.join( '</span><span class="line">' ) + '</span>';
import( /* webpackChunkName: "scripts/jQuery.textillate" */ './loadJQueryTextillate' ).then( () => {
$el.html( el_html ).addClass( 'opaque' ).children( '.line' ).textillate( {
in : {
effect : $el.data( 'in-effect' ) || 'fadeInLeft',
delay : $el.data( 'delay' ) || 12,
},
} );
} );
}
export default () => {
const $els = $( '.tlt' );
if ( 0 === $els.length ) {
return false;
}
$els.each( function( index, elem ) {
maybeAnimateText( elem );
} );
return true;
};
Here is the JS entry script (app.js):
window.$ = window.jQuery = require( 'jquery' );
import 'bootstrap';
import checkAnimatedText from './modules/animatedText';
$( window ).on( 'load', () => {
checkAnimatedText();
} );
Finally, here is the Laravel Mix config script (webpack.mix.js):
const mix = require( 'laravel-mix' );
require( 'laravel-mix-versionhash' );
// Public path helper
const publicPath = path => `${mix.config.publicPath}/${path}`;
// Source path helper
const src = path => `resources/assets/${path}`;
// Public Path
mix
.setPublicPath( './dist' )
.setResourceRoot( `/wp-content/themes/magnetar/${mix.config.publicPath}/` )
.webpackConfig( {
module : {
rules : [ {
test : /animate\.css$/,
use : [ {
loader : "style-loader/useable",
}, { loader : "css-loader" } ],
} ],
},
output : { publicPath : mix.config.resourceRoot },
} );
// Browsersync
mix.browserSync( 'magnetar.localhost' );
// Styles
mix.sass( src`styles/app.scss`, 'styles' );
// Assets
mix.copyDirectory( src`images`, publicPath`images` )
.copyDirectory( src`fonts`, publicPath`fonts` );
// JavaScript
mix.js( src`scripts/app.js`, 'scripts' );
//.extract();
// Autoload
/*mix.autoload( {
jquery : [ '$', 'window.jQuery' ],
} );*/
// Source maps when not in production.
mix.sourceMaps( false, 'source-map' );
// Hash and version files in production.
mix.versionHash( { length : 16 } );
Compiler output:
ERROR in ./node_modules/animate.css/animate.css (./node_modules/css-loader??ref--6-1!./node_modules/postcss-loader/src??ref--6-2!./node_modules/style-loader/useable.js!./node_modules/css-loader!./node_modules/animate.css/animate.css)
Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError
(1:1) Unknown word
> 1 | var refs = 0;
| ^
2 | var dispose;
3 | var content = require("!!../css-loader/index.js!./animate.css");
EDIT: Updated contents of loadJQueryTextillate.js, webpack.mix.js and compiler output.
You can try style-loader/useable to dynamically load css file. In your script code, you should use style.use() to make style useable or use style.unuse() to make style disable.
The following code shows how you should do to use style-loader/useable.
webpack.config.js
{
module: {
rules: [
{
test: /\.css$/,
exclude: /\.useable\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
],
},
{
test: /\.useable\.css$/,
use: [
{
loader: "style-loader/useable"
},
{ loader: "css-loader" },
],
},
],
},
}
file you want to dynamically load animate.css
import style form './animate.css';
// make aniamte.css useable
style.use();
// make animate.css disable
style.unuse();

How can I get a list of long Wikipedia articles?

I know Special:LongPages and I've seen https://en.wikipedia.org/w/api.php and https://en.wikipedia.org/api/rest_v1/.
Is there a way to get long articles (or articles ordered by size) from one of the APIs?
For many special pages, including LongPages, the API equivalent is the querypage module:
let query = {
action: 'query',
list: 'querypage',
qppage: 'Longpages',
format: 'json',
formatversion: 2,
origin: '*'
};
function doQuery( query ) {
return $.get( 'https://en.wikipedia.org/w/api.php', query ).then( function ( data ) {
console.log( data.query.querypage.results.map( function ( item ) {
return item.title;
} ) );
if ( data.continue ) {
let continueQuery = $.extend( {}, query, data.continue );
return doQuery( continueQuery );
}
} );
}
doQuery( query );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to populate empty array with a method in Vue

I'm trying to populate an empty array with a declared array variable in a computed function. I tried this but with no luck:
data: {
hashtags: []
},
computed: {
filteredHashtags () {
var defaultHashtags = [ '#hr', '#acc', '#sales' ];
var fHashtags =
_.chain( messages )
.pluck( 'hashtags' )
.flatten()
.map(
function ( tag ) {
return tag && tag.trim() ? '#' + tag : null; })
.filter( Boolean )
.value();
fHashtags = _.union( fHashtags, defaultHashtags );
return data.hashtags = fHashtags;
}
}
also, is there a better method to approach this?
A computed property isn't really a good use case for this, because the computed value has to be referenced in order for it to be called. Instead, just make it a method and call it the method when your Vue is created.
data: {
hashtags: []
},
methods: {
filterHashtags() {
// commented out stuff
// set the data property with the filtered values
this.hashtags = fHashtags;
}
},
created(){
this.filterHashtags();
}

Jquery Datatables expand row and get detail via Ajax

Is it possible to get the detail for each row through Ajax?
I found a starting point here:
http://datatables.net/release-datatables/examples/api/row_details.html
but it doesn't use ajax.
I'm thinking about modifying fnFormatDetails() function and place the ajax call there.
But i'm looking for another better answer.
Thanks.
It's very simple. All you have to do is put your details in a separate field within the "data" array:
E.g. your JSON might look like as follows:
{
"draw": "${drawId}",
"recordsTotal": "${totalRecords}",
"recordsFiltered": "${filteredRecords}",
"data": [
{
"empName": "${employee.name}",
"empNumber": "${employee.number}",
"empEmail": "${employee.email}",
"extraDetails" : [
["${employee.salary}", "${employee.title}"]
]
}
]
}
Then in your javascript, you can simply access this extra details by using JavaScript arrays. E.g.
var row = employeeTable.row( tr );
var rowData = row.data();
alert(rowData.extraDetails[0][0]);
alert(rowData.extraDetails[0][1]);
You need not to go for ajax if you have the data in your row.
Try oTable.fnGetData(rowIndexor|trNode)
you can try this and it will work.
First: create your datatable.
var table = $('#myTable').DataTable( {
ajax: '/api/staff',
columns: [
{
className: 'details-control',
orderable: false,
data: null,
defaultContent: ''
},
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "salary" }
],
order: [[1, 'asc']] } );
Second: Event handlers
$('#myTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
row.child.hide();
tr.removeClass('shown');
}
else {
row.child( format(row.data()) ).show();
tr.addClass('shown');
} } );
Third: Ajax request and formatting the response
function format ( rowData ) {
var div = $('<div/>')
.addClass( 'loading' )
.text( 'Loading...' );
$.ajax( {
url: '/api/staff/details',
data: {
name: rowData.name
},
dataType: 'json',
success: function ( json ) {
div
.html( json.html )
.removeClass( 'loading' );
}
} );
return div; }
you can pass any row argument to format method.
Check This For More Details

AutoComplete - yii

I am trying to add a field with auto complete functionality , I have used javascript for this
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css " />
<script src="http://code.jquery.com/jquery-1.8.2.js "></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js "></script>
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
function split( val ) {
//document.write(val.length);
return val.split( /,\s*/ );
}
function extractLast( term ) {
//echo (term.length);
//document.write(term.length);
return split( term ).pop();
}
$( "#Tag_tag_name" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
var a=0;
// if (event.keyCode === $.ui.keyCode.TAB)
// {
// a=a+1;
// }
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
// if (event.keyCode === $.ui.keyCode.P)
// {
// alert(a);
// }
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
Now What I want tot do is instead of this static values in AvaialbleTags variable I want values from database ? Plus I want to limit three values to be add by the user.
Can anyone help me with this ?
Here is what i am using multicomplete
$this->widget('ext.widgets.MultiComplete', array(
'model'=>$model,
'attribute'=>$attribute,
'splitter'=>',',
'sourceUrl'=>$this->createUrl($url),
// additional javascript options for the autocomplete plugin
'options'=>array(
'minLength'=>'1',
),
'htmlOptions'=>array(
'size'=>'60'
),
));