「JavaScript」カテゴリーアーカイブ

芸人の中で一番JavaScriptに詳しいのではないでしょうか。

Angular2 for TypeScriptのお勉強-sample(8)【requireTemplate and TemplateUrlの違い。moduleIdとは】

フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強
フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強

templateとtemplateUrlは知っていたのですが、

templateUrl

1、
@Component({
selector : 'fafa-faf',
moduleId : module.id,
templateUrl : '.app/app.childComponent'
})

とする場合と

require template

2、
@Component({
selector : 'fafa-faf',
moduleId : module.id,
template : require('.app/app.childComponent'),
moduleId: module.id
})
とする場合は何が違うのでしょう。
ここによると

1の場合はhtmlへの PATH。
2の場合はstring。文字列が返り値。templateに割り当てている。なので同じ結果に。

requireを使いたいときは"template"としなくてはいけません。

moduleId

moduleIdを付けることで、Angularがルートからファイルを探し始める代わりに現在のフォルダから探し始めます。

つまり
app/app.childComponent.html
app/app.childComponent.ts

こういう階層になっていた場合
moduleId: module.id
を設定するだけで

Angularは呼び出し元のファイルから同階層のファイルを探す。
なので記述が

2の例だと
@Component({
selector : 'fafa-faf',
moduleId : module.id,
template : require('app.childComponent'),
moduleId: module.id
})

こうなるわけ。見やすい!!
moduleIdについてはここ

今回は
・templateUrlとtemplate requireの違い
・moduleId

を覚えました。

moduleIdは積極的に設定しましょう!

今回のコード

でわまた〜〜

前のAngular2記事へ
次のAngular2記事へ

他のAngular2記事

他のjavascript記事

Angular2 for TypeScriptのお勉強-sample(5)【ngClass,*ngIf,directives】

フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強
フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強

ngClass,*ngIfはよく使う。ので最初に押さえておきたい。。

 

今回やったこと

・子component(directives)として親で描画

・クリック時にisCheckedを判定してfalseだったら子componentをhide

・isCheckedによってスタイルとテキストを変える

import { Component } from '@angular/core';
import { ChildComponent } from './app.childComponent';
import { Ngif } from 'angular/common';

@Component({
selector: 'my-app',
template: `
<h1 style="height:45px">WIP</h1>
<div [style.color]="isChecked ? '#e3e3e3': 'red'">{{isChecked ?'now is true' : 'now is false'}}</div>
<child-component *ngIf="isChecked"></child-component>
<input type="checkbox" [(ngModel)]="isChecked" />
{{isChecked}}
`,
directives: [ChildComponent]
})
export class AppComponent {
isChecked:boolean;
constructor(){
this.isChecked = !this.isChecked;
}
}

・サブツリーを削除する

今回のコード

でわまた〜〜

次のAngular2記事へ

他のAngular2記事

他のjavascript記事

Angular2 for TypeScriptのお勉強-sample(4)【双方向バインディング】

フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強
フロントエンドエンジニア芸人もりたけんじのAngular2とTypeScriptのお勉強

Angularを使い始めてこれが一番驚いた記憶あるのですが、Angular2ではどのように書くのかと思い
チュートリアルのここらへん読みました。というか多分ここのページが全てだと思うので今後ここのやつ一通りやりたいと思います。

input内に入力するとその場でdirtyチェック?走ってリアルタイムに書き出されるのはAngularでもそうでしたが、
ngModelを[(ngModel)]="name"として定義するのですね。

また(click)="save($event)"としてクリック時$eventを渡すのですね($を書き忘れてなんでだってなりました)

今回のコード

でわまた〜〜

次のAngular2記事へ

他のAngular2記事

他のjavascript記事

【JavaScript】getClientRectsとgetBundingClientRectの使い方、違い

「getClientRectsとgetBundingClientRectの使い方、違い」で検索したら日本語記事がなかったので下の参考をざっくり翻訳して書こうと思いました。

getClientRects

戻り値 : ClientRectList

var rect = document.getElementById("myElement").getClientRects();

このような要素を取得した場合、
ClientRectListの中身

{
0: ClientRect,←この中身は下で説明
length: 1,
item: item()
}

getBundingClientRect

戻り値 : ClientRect
中身

{
bottom:
height:
left:
top:
width:
}

を持ちます。

ClientRectて??
前出のgetBundingClientRectで返されるListのインデックス0のオブジェクト。

https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIDOMClientRect
・属性にbottom, height, left, right, top, width等を持つオブジェクト
ここの属性にアクセスしてveiwportをrelativeとした要素領域情報(rectangle boxの幅や高さ)を取得できる
・ここでの位置情報はスクロールされると変わる

・値は読み込み専用
※呼び方が変わる、ClientRectだったり、DOMRectだったり、TextRectangleだったり
・ブラウザ互換性は chrome 1.0 Firefox:3.0 IE 4 Opera 4 Safari 4

何が嬉しいか。
var fafa = document.getElementById('fafa')
fafa.offsetLeft
fafa.offsetTop;
fafa.offsetWidth;
fafa.offsetHeight
などのオブジェクトと併せて使うことで威力を発揮する

実際使ってみる
jsfiddleにこちらhttps://getfirebug.com/firebug-lite-debug.jsをExternalResourcesとして追加するとデバッグできる。consoleとかみながらできる

https://jsfiddle.net/kenjimorita/mm9uosog/

他のJavaScript記事

参考
https://stackoverflow.com/questions/18780139/how-to-get-bounding-box-for-div-element-in-jquery
https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects
https://msdn.microsoft.com/en-us/library/ms536435(VS.85).aspx
https://msdn.microsoft.com/en-us/library/ms536433(v=vs.85).aspx

【JavaScript】JavaScript問題集

以前書いたJavaScript問題集githubのこっちに見やすいようにリプレイスした。
こっちならスマホでも整っていて見やすいし、自分自身これを傍らに置きながら勉強できる。。

簡単なこれらの勉強をもっとスムーズにするためにWebアプリでも作って、問題をシャッフルして答えたら次、みたいなの作ろうと思っている。
どうやったらJS技術が今よりちょっとでも上がるかとか、ストレスなく勉強できるかを考えている

「特定の値以外の値」を返す

googleで表題の様なキーワードで探したら見当たらずなのでページ作りました。
下の用にfilterとsliceでなんとかします。
非破壊メソッドを使ってnumを壊さないようにしています。

あと全然関係ないけどQiitaにリツイートされたので嬉しかったので張っておきます。

「特定の値以外の値」を返すコード

[code lang="javascript"]

var num = [0,1,2];
//任意の値を返す関数
function select(num,i){
return num.slice(i)
};

//任意の値以外を返す関数
function unselect(num, i){
var selected = num.filter(function(num, inde){
return inde !== i
});
return selected
}
select(num, 2);
//[2]

num
//[0, 1, 2] 壊れていない

unselect(num, 1)
//[0, 2]

num
//[0, 1, 2] 壊れていない
[/code]

【ES6】適当に試したり。正規表現とか

全コード

[code lang="javascript"]

function getKey(k) {
return `${k}`;
}

const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};

console.log(obj)
///////////////////////////

function f(x, ...y) {//ここで受け取らない分が配列の要素としてyになる
// y is an Array
console.log(y)//["hello","true"]
return x * y.length;
}
const r1 = f(3, "hello", true) == 6
console.log(r1);//true

//////////////////////////////

function f(x, y, z, t, p) {//インデックス順に受け取る
console.log(z);
return x + y + z;
}
// Pass each elem of array as argument
//const arry = [1,2,3,5,6];
//f(...arry) == 6
//or
f(...[1,2,4]);

///////////////////////////////

let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
console.log([pre, cur] = [cur, pre + cur]);
return { done: false, value: cur }
}
}
}
}

//////////////////////

let [a, b, c] = []
console.log(a,b,c);
typeof b

function getSomething(){
return {
first: 1,
second: 2,
third: 3
}
}

var { first, second, third } = getSomething();
console.log(first)

console.log("repeat".repeat(2));

console.log(["morita","kenji","fafafa"].findIndex(x => x == "fafafa"))

console.log(["A","B","C"].map(x => Array.of(x)));

console.log(['a', 'b', 'c'].fill('kenji', 1, 2));

const i = [3, 0, 6, -1].find(x=> x < 0);
console.log(i)

function* idMaker(){
var index = 0;
while(true)
yield index++;
}

const gen = idMaker();
console.log(gen)
////////////////////////////

const str = "わたしの名前は「もりた」です。あだなは「もりけん」です";

const re = /「.*?」/ig;

const myRe=/ken*/g;
const str2 = "fafakenfafkenji";
let array;
while ((array = myRe.exec(str2)) !== null) {
let msg = array[0] + " を見つけました。";
msg += "次のマッチは " + myRe.lastIndex + " からです。";
console.log(msg);
}

const str3 = "<img src='fafa.com'>"
const str4 = "<p>"
const reg2 = /<(\S+)(\s+.+)?>/;
const reg3 = /<(?:\S+)(?:\s+.+)?>/;
const re2 = str3.match(reg2);
const re3 = str3.match(reg3);
const re4 = str4.match(reg2);
console.log(re2);console.log(re2[0]);
console.log(re3);console.log(re3[0]);
console.log(re4);console.log(re4[0]);

const str222 = "わたしの名前は「もりた」です。あだなは「もりけん」です";

const re222 = /「(.+?)」/ig;

let result;
while ((result = re222.exec(str222)) !== null){
console.log(result[0],"ここ")
}

const nen = "西暦1980年の3581歳です";
const reg1 = /\d+(?=年)/;
console.log(nen.match(reg1))

const string3 = "washable reasonable accessible assemble answerable";
const reg5 = /\b\w+(?=able\b)/g;
console.log(string3.match(reg5));

const nen1 = "ケンジは昭和55年生まれの35歳であり、ケンジの母は昭和22年生まれの64歳である"
const reg6 = /\d+(?![年\d])/g;
console.log(nen1.match(reg6));

const str5 = "あの客はよく柿食う客だ";
const res5 =str5.match(/あの(.+)はよく柿食う\1だ/);
console.log(res5);

const tag = "<div><h1>kenjimorita.jp</h1></div>";

console.log(/<(\w+)><(\w+)>kenjimorita.jp<\/\2><\/\1>/.test(tag))

// const str6 = "西暦2010年は平成22年です。西暦1980年は昭和55年です。";
// console.log(str6.match(/(?<=昭和|平成)\d+/))

const str7 = "My name is Taro Suzuki and I am a researcher at ABC.";

console.log(str7.match(/\ba\w*\b/g));

var falseValue = new Boolean(false);
console.log(falseValue)//false

var fafa = null;
console.log(typeof fafa)//Object
console.log(fafa == undefined)//等値演算子ではtrueになってしまう
console.log(fafa === null);//true //同値演算子を使う
[/code]

【ECMAScript2015(ES6)】後で猫に教えてあげたいES6の「Generators(ジェネレーター)とIterator(イテレータ)」

昨日はSymbol(シンボル)でしたが、今日はGeneratorsとIterator。
babel立ち上げてコード確認しながらやりました。

ジェネレータってなにかって再帰処理を簡単にしてくれるものなんですね。
そのイテレータオブジェクトを返す関数がジェネレータ

ジェネレータを扱うにはイテレータを理解する必要があるようです。
続きを読む